"""E-Mail-Akquise für KI Web Studio – Vorlagen, Suche, Validierung."""

from __future__ import annotations

import re
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

from jam.ki_studio_marketing import EXTRAS_LINE, PRICE_REGULAR, PRICE_SONDER, SITE_URL, sonderangebot_short

LEADS_DIR = Path(__file__).resolve().parents[1] / "data" / "ki-web-studio-marketing"

EMAIL_RE = re.compile(r"[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}")
SKIP_EMAIL = re.compile(
    r"(noreply|no-reply|donotreply|example\.com|wix\.com|sentry\.|\.png|\.jpg|"
    r"facebook\.com|instagram\.com|google\.com|gmail\.com\/|schema\.org|"
    r"duckduckgo\.com|brave\.com|bing\.com|microsoft\.com|yahoo\.com)",
    re.I,
)


def email_subject() -> str:
    return f"🔥 Website Sonderangebot – nur {PRICE_SONDER} € statt {PRICE_REGULAR:.2f} €"


def email_body(name: str, city: str, *, utm_city: str = "") -> str:
    city_bit = city or "Ihrer Region"
    utm = urllib.parse.urlencode(
        {
            "utm_source": "outreach",
            "utm_medium": "email",
            "utm_campaign": "de_email",
            "utm_content": (utm_city or city).replace(" ", "_")[:40],
        }
    )
    link = f"{SITE_URL}/?{utm}"
    return (
        f"Hallo,\n\n"
        f"ich bin David von KI Web Studio ({SITE_URL}).\n\n"
        f"Ich habe gesehen, dass {name} in {city_bit} noch keine eigene Website hat "
        f"(oder nur auf Portalen gelistet ist).\n\n"
        f"{sonderangebot_short()} – inkl. Impressum & mobiloptimiert.\n"
        f"{EXTRAS_LINE}\n\n"
        f"Mehr Infos: {link}\n\n"
        f"Hätten Sie Interesse an einem kurzen, unverbindlichen Beispiel?\n\n"
        f"Viele Grüße\n"
        f"David Prechtel\n"
        f"KI Web Studio\n"
        f"{SITE_URL}\n"
    )


def mailto_url(to: str, subject: str, body: str) -> str:
    return (
        f"mailto:{urllib.parse.quote(to)}?"
        f"subject={urllib.parse.quote(subject)}&"
        f"body={urllib.parse.quote(body)}"
    )


def normalize_email(raw: str) -> str:
    return raw.strip().lower()


def is_plausible_email(email: str) -> bool:
    e = normalize_email(email)
    if not EMAIL_RE.fullmatch(e):
        return False
    if SKIP_EMAIL.search(e):
        return False
    if e.endswith((".de", ".com", ".net", ".org", ".eu", ".info", ".biz")):
        return True
    return "." in e.split("@")[-1]


def extract_emails(text: str) -> list[str]:
    found: list[str] = []
    seen: set[str] = set()
    for m in EMAIL_RE.findall(text or ""):
        e = normalize_email(m)
        if e in seen or not is_plausible_email(e):
            continue
        seen.add(e)
        found.append(e)
    return found


def _fetch_search_html(url: str, *, post_data: bytes | None = None, timeout: float = 15.0) -> str:
    req = urllib.request.Request(
        url,
        data=post_data,
        method="POST" if post_data else "GET",
        headers={
            "User-Agent": "Mozilla/5.0 (compatible; ki-web-studio-email/1.0)",
            "Accept-Language": "de-DE,de;q=0.9",
            **({"Content-Type": "application/x-www-form-urlencoded"} if post_data else {}),
        },
    )
    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return resp.read().decode("utf-8", errors="replace")
    except (urllib.error.URLError, TimeoutError, OSError):
        return ""


def search_email_online(name: str, city: str, *, timeout: float = 15.0) -> str:
    """Websuche nach Impressum/Kontakt – kostenlos, ohne API-Key."""
    queries = [
        f'"{name}" {city} impressum email',
        f'"{name}" {city} kontakt @',
        f"{name} {city} 11880 email",
    ]
    for q in queries:
        # DuckDuckGo HTML
        html = _fetch_search_html(
            "https://html.duckduckgo.com/html/",
            post_data=urllib.parse.urlencode({"q": q}).encode(),
            timeout=timeout,
        )
        hits = extract_emails(html)
        if hits:
            return hits[0]
        # Brave Search (Fallback)
        brave_q = urllib.parse.quote(q)
        html2 = _fetch_search_html(f"https://search.brave.com/search?q={brave_q}", timeout=timeout)
        hits2 = extract_emails(html2)
        if hits2:
            return hits2[0]
        time.sleep(1.2)
    return ""
