"""
Public domain: landing page, marketing pages, legal pages, feedback.
"""
from pathlib import Path

from quart import Blueprint, g, render_template, request, session

from ..core import check_rate_limit, csrf_protect, execute, fetch_all, fetch_one
from ..i18n import get_translations

bp = Blueprint(
    "public",
    __name__,
    template_folder=str(Path(__file__).parent / "templates"),
)


async def _supplier_counts():
    """Fetch aggregate supplier stats for landing/marketing pages."""
    total = await fetch_one("SELECT COUNT(*) as cnt FROM suppliers")
    countries = await fetch_one(
        "SELECT COUNT(DISTINCT country_code) as cnt FROM suppliers"
    )
    return (
        total["cnt"] if total else 0,
        countries["cnt"] if countries else 0,
    )


@bp.route("/")
async def landing():
    total_suppliers, total_countries = await _supplier_counts()
    return await render_template(
        "landing.html",
        total_suppliers=total_suppliers,
        total_countries=total_countries,
    )


@bp.route("/features")
async def features():
    return await render_template("features.html")


@bp.route("/terms")
async def terms():
    lang = g.get("lang", "en")
    return await render_template(f"terms_{lang}.html")


@bp.route("/privacy")
async def privacy():
    lang = g.get("lang", "en")
    return await render_template(f"privacy_{lang}.html")


@bp.route("/about")
async def about():
    return await render_template("about.html")


@bp.route("/market-score")
async def market_score():
    return await render_template("market_score.html")


@bp.route("/imprint")
async def imprint():
    lang = g.get("lang", "en")
    return await render_template(f"imprint_{lang}.html")


@bp.route("/suppliers")
async def suppliers():
    total_suppliers, total_countries = await _supplier_counts()

    # Live stats
    calc_requests = await fetch_one("SELECT COUNT(*) as cnt FROM scenarios WHERE deleted_at IS NULL")
    avg_budget = await fetch_one(
        "SELECT AVG(budget_estimate) as avg FROM lead_requests WHERE budget_estimate > 0 AND lead_type = 'quote'"
    )
    active_suppliers = await fetch_one(
        "SELECT COUNT(*) as cnt FROM suppliers WHERE tier IN ('growth', 'pro') AND claimed_by IS NOT NULL"
    )
    monthly_leads = await fetch_one(
        "SELECT COUNT(*) as cnt FROM lead_requests WHERE lead_type = 'quote' AND created_at >= date('now', '-30 days')"
    )

    # Lead feed preview — 3 recent verified hot/warm leads, anonymized
    preview_leads = await fetch_all(
        """SELECT facility_type, court_count, country, timeline, budget_estimate,
                  heat_score, glass_type, build_context, financing_status
           FROM lead_requests
           WHERE lead_type = 'quote' AND verified_at IS NOT NULL
                 AND heat_score IN ('hot', 'warm')
           ORDER BY created_at DESC LIMIT 3"""
    )

    return await render_template(
        "suppliers.html",
        total_suppliers=total_suppliers,
        total_countries=total_countries,
        calc_requests=calc_requests["cnt"] if calc_requests else 0,
        avg_budget=int(avg_budget["avg"]) if avg_budget and avg_budget["avg"] else 0,
        active_suppliers=active_suppliers["cnt"] if active_suppliers else 0,
        monthly_leads=monthly_leads["cnt"] if monthly_leads else 0,
        preview_leads=preview_leads,
    )


# =============================================================================
# Feedback
# =============================================================================

@bp.route("/feedback", methods=["POST"])
@csrf_protect
async def feedback():
    """Handle feedback submission. Returns HTMX partial."""
    t = get_translations(g.get("lang", "en"))

    # Rate limit: 5 per hour per IP
    key = f"feedback:{request.remote_addr}"
    allowed, _info = await check_rate_limit(key, limit=5, window=3600)
    if not allowed:
        return f'<p style="font-size:0.8125rem;color:#D97706;padding:8px">{t["flash_feedback_rate_limit"]}</p>'

    form = await request.form
    message = form.get("message", "").strip()
    if not message:
        return f'<p style="font-size:0.8125rem;color:#DC2626;padding:8px">{t["flash_feedback_empty"]}</p>'

    page_url = form.get("page_url", "")
    user_id = session.get("user_id")
    umami_id = form.get("umami_id", "") or None
    contact = form.get("contact", "").strip() or None

    await execute(
        "INSERT INTO feedback (user_id, page_url, message, umami_id, contact) VALUES (?, ?, ?, ?, ?)",
        (user_id, page_url, message, umami_id, contact),
    )

    return f'<p style="font-size:0.8125rem;color:#16A34A;padding:12px;text-align:center;font-weight:600">{t["flash_feedback_success"]}</p>'
