import re
import unicodedata
from datetime import date, datetime

import nh3
from flask import request

SITE_TZ = "America/Chicago"  # Houston time: decides when an event moves to "Past Events"


def today_local():
    """Today's date in Houston, whatever the server's own time zone is."""
    try:
        from zoneinfo import ZoneInfo
        return datetime.now(ZoneInfo(SITE_TZ)).date()
    except Exception:
        return date.today()


ALLOWED_TAGS = {"p", "br", "strong", "b", "em", "i", "u", "ul", "ol", "li", "a",
                "h3", "h4", "blockquote"}


def clean_html(html):
    return nh3.clean(html or "", tags=ALLOWED_TAGS,
                     attributes={"a": {"href", "title", "target"}},
                     link_rel="noopener noreferrer")


def slugify(text):
    text = unicodedata.normalize("NFKD", text or "").encode("ascii", "ignore").decode()
    return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "album"


def client_ip():
    return (request.access_route[0] if request.access_route else request.remote_addr) or ""


def text_to_html(text):
    """Turn plain paragraphs (blank-line separated) into <p> HTML."""
    parts = [p.strip() for p in re.split(r"\n\s*\n", text or "") if p.strip()]
    return "".join(f"<p>{p}</p>" for p in parts)
