"""PWA-Manifest & Android TWA-Vorbereitung für Jami-Dating."""

from __future__ import annotations

import json
from pathlib import Path

from jam.jami_domain import resolve_site_url

APP_NAME = "Jami-Dating"
APP_SHORT_NAME = "Jami"
APP_PACKAGE = "de.jamidating.app"
THEME_COLOR = "#0a0610"
BG_COLOR = "#0a0610"


def manifest_json(*, site_url: str | None = None) -> str:
    base = (site_url or resolve_site_url()).rstrip("/")
    data = {
        "name": APP_NAME,
        "short_name": APP_SHORT_NAME,
        "description": (
            "Echte Singles. Echte Dates. Kostenlos registrieren, matchen und chatten – "
            "ohne Fake-Moderatoren."
        ),
        "start_url": "/",
        "scope": "/",
        "display": "standalone",
        "orientation": "portrait-primary",
        "lang": "de-DE",
        "dir": "ltr",
        "theme_color": THEME_COLOR,
        "background_color": BG_COLOR,
        "categories": ["social", "lifestyle"],
        "icons": [
            {
                "src": "images/jami-dating-logo.png",
                "sizes": "512x512",
                "type": "image/png",
                "purpose": "any",
            },
            {
                "src": "images/jami-dating-logo.png",
                "sizes": "512x512",
                "type": "image/png",
                "purpose": "maskable",
            },
        ],
        "screenshots": [],
        "prefer_related_applications": False,
        "id": "/",
    }
    return json.dumps(data, ensure_ascii=False, indent=2) + "\n"


def _load_android_fingerprints() -> list[str]:
    root = Path(__file__).resolve().parents[1]
    fps: list[str] = []

    multi = root / "data" / "android-sha256-fingerprints.json"
    if multi.is_file():
        try:
            data = json.loads(multi.read_text(encoding="utf-8"))
            for key in ("upload", "play_app_signing", "debug"):
                fp = str(data.get(key, "")).strip().upper()
                if fp and "HIER" not in fp and fp not in fps:
                    fps.append(fp)
            for fp in data.get("all") or []:
                fp = str(fp).strip().upper()
                if fp and fp not in fps:
                    fps.append(fp)
        except (OSError, json.JSONDecodeError, TypeError):
            pass

    fp_path = root / "data" / "android-sha256-fingerprint.txt"
    if fp_path.is_file():
        fp = fp_path.read_text(encoding="utf-8").strip().upper()
        if fp and "HIER" not in fp and fp not in fps:
            fps.append(fp)
    return fps


def assetlinks_json(*, sha256_fingerprints: list[str] | None = None) -> str:
    fps = sha256_fingerprints or _load_android_fingerprints()
    if not fps:
        fps = [
            "HIER_SHA256_FINGERPRINT_NACH_APP_SIGNATUR_EINTRAGEN",
        ]
    data = [
        {
            "relation": [
                "delegate_permission/common.handle_all_urls",
                "delegate_permission/common.get_login_creds",
            ],
            "target": {
                "namespace": "android_app",
                "package_name": APP_PACKAGE,
                "sha256_cert_fingerprints": fps,
            },
        }
    ]
    return json.dumps(data, ensure_ascii=False) + "\n"


def pwa_head_tags() -> str:
    return "\n  ".join(
        [
            '<link rel="manifest" href="/manifest.webmanifest"/>',
            f'<meta name="theme-color" content="{THEME_COLOR}"/>',
            '<meta name="mobile-web-app-capable" content="yes"/>',
            f'<meta name="application-name" content="{APP_SHORT_NAME}"/>',
            '<meta name="apple-mobile-web-app-capable" content="yes"/>',
            '<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>',
            f'<meta name="apple-mobile-web-app-title" content="{APP_SHORT_NAME}"/>',
        ]
    )


def write_pwa_files(root: Path, *, site_url: str | None = None) -> None:
    root.mkdir(parents=True, exist_ok=True)
    (root / "manifest.webmanifest").write_text(manifest_json(site_url=site_url), encoding="utf-8")
    well_known = root / ".well-known"
    well_known.mkdir(parents=True, exist_ok=True)
    (well_known / "assetlinks.json").write_text(assetlinks_json(), encoding="utf-8")
