"""SEO, Sitemap und Structured Data für Jami-Dating."""

from __future__ import annotations

import json
from pathlib import Path

from jam.jami_domain import load_secrets, resolve_site_url
from jam.jami_pwa import pwa_head_tags

SITE_NAME = "Jami-Dating"
TAGLINE = "Echte Singles. Echte Dates. Keine Fake-Moderatoren."
DESCRIPTION = (
    "Jami-Dating: Kostenlos registrieren, Singles in deiner Nähe entdecken, "
    "matchen und chatten. 100 Gratis-Coins zum Start. Nur echte Personen – "
    "garantiert ohne Chat-Moderatoren. Dating-App aus Deutschland."
)

FAQ_ITEMS: tuple[tuple[str, str], ...] = (
    (
        "Ist Jami-Dating kostenlos?",
        "Ja. Die Registrierung ist kostenlos und du erhältst 100 Gratis-Coins zum Start. "
        "Chat-Nachrichten kosten 10 Coins – fair und transparent.",
    ),
    (
        "Nutzt Jami-Dating Fake-Profile oder Chat-Moderatoren?",
        "Nein. Bei Jami-Dating chattest du nur mit registrierten echten Nutzerinnen und Nutzern. "
        "Wir setzen keine Moderatoren ein, die vorgeben, Singles zu sein.",
    ),
    (
        "Für wen ist Jami-Dating geeignet?",
        "Für Erwachsene ab 18 Jahren in Deutschland und Europa, die ernsthaft flirten, "
        "neue Leute kennenlernen oder sich verlieben möchten.",
    ),
    (
        "Wie finde ich Singles in meiner Nähe?",
        "Nach der Registrierung siehst du Profile sortiert nach Entfernung in km – "
        "plus Herkunft (Stadt/Land) auf jedem Profil.",
    ),
    (
        "Wie sicher ist Jami-Dating?",
        "Du kannst Profile melden und blockieren. Wir speichern nur, was für den Betrieb nötig ist. "
        "Details in der Datenschutzerklärung.",
    ),
    (
        "Wie kaufe ich Coins?",
        "Über Stripe Checkout (Karte, SEPA, Klarna, PayPal je nach Freigabe) – "
        "Pakete ab 2,99 € für 100 Coins.",
    ),
)


def _extras() -> dict:
    return load_secrets()


def head_markup(site_url: str | None = None) -> str:
    base = (site_url or resolve_site_url()).rstrip("/")
    extras = _extras()
    ga_id = str(extras.get("google_analytics_id", "")).strip()
    g_verify = str(extras.get("google_site_verification", "")).strip()
    image = f"{base}/images/jami-dating-logo.png"
    title = f"{SITE_NAME} – Kostenlos Singles kennenlernen | Echte Dates"
    keywords = (
        "Dating App, Singles kennenlernen, Partner finden, Flirt App, "
        "Dating Deutschland, echte Singles, Match App, Chat Dating, Jami Dating"
    )

    ld_web = {
        "@context": "https://schema.org",
        "@type": "WebSite",
        "name": SITE_NAME,
        "url": base,
        "description": DESCRIPTION,
        "inLanguage": "de-DE",
        "potentialAction": {
            "@type": "SearchAction",
            "target": f"{base}/#start",
            "query-input": "required name=search_term_string",
        },
    }
    ld_org = {
        "@context": "https://schema.org",
        "@type": "Organization",
        "name": SITE_NAME,
        "url": base,
        "logo": image,
        "description": TAGLINE,
    }
    ld_faq = {
        "@context": "https://schema.org",
        "@type": "FAQPage",
        "mainEntity": [
            {
                "@type": "Question",
                "name": q,
                "acceptedAnswer": {"@type": "Answer", "text": a},
            }
            for q, a in FAQ_ITEMS
        ],
    }

    lines = [
        f'<meta name="description" content="{DESCRIPTION}"/>',
        f'<meta name="keywords" content="{keywords}"/>',
        '<meta name="robots" content="index, follow, max-image-preview:large"/>',
        f'<meta name="author" content="{SITE_NAME}"/>',
        f'<link rel="canonical" href="{base}/"/>',
        f'<title>{title}</title>',
        f'<meta property="og:type" content="website"/>',
        f'<meta property="og:site_name" content="{SITE_NAME}"/>',
        f'<meta property="og:title" content="{title}"/>',
        f'<meta property="og:description" content="{DESCRIPTION}"/>',
        f'<meta property="og:url" content="{base}/"/>',
        f'<meta property="og:image" content="{image}"/>',
        '<meta property="og:locale" content="de_DE"/>',
        '<meta name="twitter:card" content="summary_large_image"/>',
        f'<meta name="twitter:title" content="{title}"/>',
        f'<meta name="twitter:description" content="{DESCRIPTION}"/>',
        f'<meta name="twitter:image" content="{image}"/>',
        '<link rel="preload" href="css/app.css" as="style"/>',
        '<link rel="icon" href="images/jami-dating-logo.png" type="image/png"/>',
        '<link rel="apple-touch-icon" href="images/jami-dating-logo.png"/>',
        pwa_head_tags(),
        '<link rel="preload" href="images/jami-dating-logo.png" as="image"/>',
        f'<script type="application/ld+json">{json.dumps(ld_web, ensure_ascii=False)}</script>',
        f'<script type="application/ld+json">{json.dumps(ld_org, ensure_ascii=False)}</script>',
        f'<script type="application/ld+json">{json.dumps(ld_faq, ensure_ascii=False)}</script>',
    ]
    if g_verify:
        lines.append(f'<meta name="google-site-verification" content="{g_verify}"/>')
    if ga_id and ga_id.startswith("G-"):
        lines.append(
            '<script>window.addEventListener("load",function(){setTimeout(function(){'
            f'var s=document.createElement("script");s.async=true;'
            f's.src="https://www.googletagmanager.com/gtag/js?id={ga_id}";'
            'document.head.appendChild(s);'
            'window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}'
            f"gtag('js',new Date());gtag('config','{ga_id}',{{'anonymize_ip':true}});"
            '},window.__jamiLite?4000:1200);},{once:true});</script>'
        )
    return "\n  ".join(lines)


def faq_section_html() -> str:
    items = "\n".join(
        f'        <details class="faq-item" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question">'
        f'<summary itemprop="name">{q}</summary>'
        f'<p itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer">'
        f'<span itemprop="text">{a}</span></p></details>'
        for q, a in FAQ_ITEMS
    )
    return f"""
    <section class="landing-section faq-section" id="faq">
      <h2>Häufige Fragen zu Jami-Dating</h2>
      <p class="sub">Alles Wichtige zu Kosten, Sicherheit und echten Singles.</p>
      <div class="faq-list">
{items}
      </div>
    </section>"""


def robots_txt(site_url: str | None = None) -> str:
    base = (site_url or resolve_site_url()).rstrip("/")
    return f"""User-agent: *
Allow: /
Disallow: /api/

Sitemap: {base}/sitemap.xml
"""


def sitemap_xml(site_url: str | None = None) -> str:
    base = (site_url or resolve_site_url()).rstrip("/")
    pages = ("/", "/impressum", "/datenschutz", "/agb")
    urls = "\n".join(
        f"""  <url>
    <loc>{base}{path}</loc>
    <changefreq>weekly</changefreq>
    <priority>{'1.0' if path == '/' else '0.5'}</priority>
  </url>"""
        for path in pages
    )
    return f"""<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
{urls}
</urlset>
"""


def write_seo_files(root: Path, site_url: str | None = None) -> None:
    url = (site_url or resolve_site_url()).rstrip("/")
    (root / "robots.txt").write_text(robots_txt(url), encoding="utf-8")
    (root / "sitemap.xml").write_text(sitemap_xml(url), encoding="utf-8")
