"""Extract contact-form notify recipients from a user's codegen prompt.

Named addresses in the request beat the workspace-owner fallback. Placeholder
domains and unrelated emails on the page (hours, maps, etc.) are ignored.
"""
from __future__ import annotations

import re

_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}")
_SKIP_DOMAINS = (
    "example.com",
    "example.org",
    "example.net",
    "p2hs.com",
    "p2hsapp.com",
    "localhost",
)
_HINTS = (
    "notif",
    "notify",
    "send to",
    "send the",
    "email to",
    "email me",
    "email us",
    "inbox",
    "recipient",
    "contact form",
    "form submission",
    "alert",
)


def notify_emails_from_text(text: str | None) -> str:
    """Return a comma-separated notify list, or empty if none should be inferred."""
    raw = text or ""
    found: list[str] = []
    seen: set[str] = set()
    for match in _EMAIL_RE.finditer(raw):
        email = match.group(0).strip().lower()
        domain = email.rsplit("@", 1)[-1]
        if any(domain == skip or domain.endswith("." + skip) for skip in _SKIP_DOMAINS):
            continue
        window = raw[max(0, match.start() - 180) : match.end() + 180].lower()
        if not any(hint in window for hint in _HINTS):
            continue
        if email in seen:
            continue
        seen.add(email)
        found.append(email)
    return ", ".join(found)
