"""Render follow-up email subject/body from schedule metadata + lead fields."""

from __future__ import annotations

from urllib.parse import urlparse

from app.config import FOLLOW_UP_GUIDE
from app.models import Lead


def _site_label(website: str | None) -> str:
    if not website:
        return "your site"
    raw = website.strip()
    if not raw.startswith(("http://", "https://")):
        raw = f"https://{raw}"
    try:
        host = urlparse(raw).hostname or website
        return host.removeprefix("www.")
    except Exception:
        return website


def render_follow_up_email(lead: Lead, fu_number: int) -> dict[str, str]:
    guide = FOLLOW_UP_GUIDE.get(fu_number) or {}
    day_label = guide.get("day_label") or f"Day ?"
    goal = guide.get("goal") or "Follow-up"
    key_cta = guide.get("key_cta") or "Happy to jump on a quick call."
    status_option = guide.get("status_option") or ""
    email_type = guide.get("email_type") or day_label
    site = _site_label(lead.website)
    first_name = (lead.contact_name or "there").split()[0]

    subject = f"Follow-up {day_label}: {lead.contact_name}"

    notes_block = ""
    if lead.notes and lead.notes.strip():
        notes_block = f"\n\n(Context from our notes: {lead.notes.strip()[:280]})"

    text = (
        f"Hi {first_name},\n\n"
        f"Quick {email_type.lower()} follow-up on {site}.\n\n"
        f"Focus this touch: {goal}.\n"
        f"{key_cta}\n"
    )
    if status_option:
        text += f"\n{status_option}\n"
    text += notes_block
    text += (
        "\n\nBest regards,\n"
        f"{(lead.our_email or 'the team').split('@')[0]}\n"
    )

    html = f"""\
<html><body style="font-family:sans-serif;line-height:1.5;color:#1a1a1a">
<p>Hi {first_name},</p>
<p>Quick <strong>{email_type}</strong> follow-up on <strong>{site}</strong>.</p>
<p><strong>Focus:</strong> {goal}<br/>{key_cta}</p>
{f'<p><em>{status_option}</em></p>' if status_option else ''}
{f'<p style="color:#555;font-size:13px">Notes: {lead.notes.strip()[:280]}</p>' if lead.notes and lead.notes.strip() else ''}
<p>Best regards,<br/>{(lead.our_email or 'the team').split('@')[0]}</p>
</body></html>
"""
    return {
        "subject": subject,
        "text": text.strip(),
        "html": html.strip(),
        "day_label": day_label,
        "goal": goal,
        "email_type": email_type,
    }
