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

from quart import Blueprint, abort, g, redirect, render_template, request, session, url_for

from ..analytics import fetch_analytics
from ..core import check_rate_limit, count_where, csrf_protect, execute, fetch_all, fetch_one
from ..i18n import get_country_name, 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."""
    return (
        await count_where("suppliers"),
        await count_where("(SELECT DISTINCT country_code FROM suppliers)"),
    )


@bp.route("/")
async def landing():
    total_suppliers, total_countries = await _supplier_counts()
    calc_requests = await count_where("scenarios WHERE deleted_at IS NULL")
    budget_row = await fetch_one(
        "SELECT COALESCE(SUM(budget_estimate), 0) AS total"
        " FROM lead_requests WHERE budget_estimate > 0 AND lead_type = 'quote'"
    )
    total_budget_millions = round((budget_row["total"] if budget_row else 0) / 1_000_000, 1)
    # Floor to nearest whole number if > 1, show one decimal if < 1
    if total_budget_millions >= 1:
        total_budget_millions = int(total_budget_millions)
    return await render_template(
        "landing.html",
        total_suppliers=total_suppliers,
        total_countries=total_countries,
        calc_requests=calc_requests,
        total_budget_millions=total_budget_millions,
    )


@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("/padelnomics-score")
async def padelnomics_score():
    return await render_template("padelnomics_score.html")


@bp.route("/market-score")
async def market_score():
    return redirect(url_for("public.padelnomics_score"), 301)


@bp.route("/opportunity-map")
async def opportunity_map():
    """Interactive padel opportunity map — country selector + location dots."""
    from ..core import is_flag_enabled
    if not await is_flag_enabled("maps", default=True):
        abort(404)
    countries = await fetch_analytics("""
        SELECT DISTINCT country_slug, country_name_en, country_code
        FROM serving.location_profiles
        WHERE city_slug IS NOT NULL
        ORDER BY country_name_en
    """)
    lang = g.get("lang", "en")
    for row in countries:
        row["country_name"] = get_country_name(row["country_name_en"], lang)
    user_cc = g.get("user_country", "")
    selected_slug = ""
    if user_cc:
        for c in countries:
            if c["country_code"] == user_cc:
                selected_slug = c["country_slug"]
                break
        countries = sorted(
            countries,
            key=lambda c: (0 if c["country_code"] == user_cc else 1, c["country_name"]),
        )
    return await render_template("opportunity_map.html", countries=countries, selected_slug=selected_slug)


@bp.route("/opportunity-map/data")
async def opportunity_map_data():
    """HTMX partial: opportunity + reference data islands for Leaflet map."""
    from ..core import is_flag_enabled
    if not await is_flag_enabled("maps", default=True):
        abort(404)
    country_slug = request.args.get("country", "")
    if not country_slug:
        return ""
    opp_points = await fetch_analytics(
        """
        SELECT location_name, location_slug, lat, lon,
               opportunity_score, market_score,
               nearest_padel_court_km, padel_venue_count, population
        FROM serving.location_profiles
        WHERE country_slug = ? AND opportunity_score > 0
        ORDER BY opportunity_score DESC
        LIMIT 500
        """,
        [country_slug],
    )
    ref_points = await fetch_analytics(
        """
        SELECT city_name, city_slug, lat, lon,
               city_padel_venue_count AS padel_venue_count,
               market_score, population
        FROM serving.location_profiles
        WHERE country_slug = ? AND city_slug IS NOT NULL
        ORDER BY city_padel_venue_count DESC
        LIMIT 200
        """,
        [country_slug],
    )
    return await render_template(
        "partials/opportunity_map_data.html",
        opp_points=opp_points,
        ref_points=ref_points,
    )


@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 count_where("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 count_where(
        "suppliers WHERE tier IN ('growth', 'pro') AND claimed_by IS NOT NULL"
    )
    monthly_leads = await count_where(
        "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,
        avg_budget=int(avg_budget["avg"]) if avg_budget and avg_budget["avg"] else 0,
        active_suppliers=active_suppliers,
        monthly_leads=monthly_leads,
        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>'
