"""
Flarlo – TikTok-ähnliche Kurzvideo-Plattform mit Nischen, KI-Moderation & Monetarisierung.

Baut statische Seite nach Documents/Flarlo.
"""

from __future__ import annotations

import json
import os
import threading
import webbrowser
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

SITE_ROOT = Path.home() / "Documents" / "Flarlo"
SITE_PORT = 8772
SITE_URL = f"http://127.0.0.1:{SITE_PORT}/"

OPERATOR = {
    "name": "David Prechtel",
    "brand": "Flarlo / KI Web Studio",
    "email": "kontakt@ki-web-studio.de",
    "web": "https://ki-web-studio.de",
}


def build_site(*, site_url: str | None = None) -> Path:
    from jam.vibeloop_assets import write_assets

    SITE_ROOT.mkdir(parents=True, exist_ok=True)
    (SITE_ROOT / "css").mkdir(exist_ok=True)
    (SITE_ROOT / "js").mkdir(exist_ok=True)

    resolved_url = (
        site_url
        or os.environ.get("FLARLO_SITE_URL")
        or os.environ.get("VIBEUP_SITE_URL")
        or os.environ.get("VIBELOOP_SITE_URL")
        or SITE_URL.rstrip("/")
    ).rstrip("/")

    config = {
        "brand": "Flarlo",
        "tagline": "Flare. Flow. Dein Clip.",
        "siteUrl": resolved_url,
        "backend": "cloudflare",
        "signupBonusCoins": 50,
        "oauth": {"google": False, "facebook": False},
        "ads": {
            "everyN": 4,
            "skipAfterSec": 5,
            "youtubeVideoIds": ["jfKfPfyJRdk", "5qap5aOk4XI", "DWcJFN3fqz0"],
        },
        "premium": {
            "label": "Flarlo+",
            "monthlyEur": 9.99,
            "noAds": True,
            "noCoins": True,
            "payment": "stripe",
        },
    }
    (SITE_ROOT / "js" / "config.json").write_text(
        json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8"
    )

    api_src = Path(__file__).resolve().parent / "vibeloop_api.js"
    (SITE_ROOT / "js" / "vibeloop-api.js").write_text(api_src.read_text(encoding="utf-8"), encoding="utf-8")
    copyright_src = Path(__file__).resolve().parent / "vibeloop_copyright.js"
    (SITE_ROOT / "js" / "vibeloop-copyright.js").write_text(
        copyright_src.read_text(encoding="utf-8"), encoding="utf-8"
    )
    community_src = Path(__file__).resolve().parent / "vibeloop_community.js"
    (SITE_ROOT / "js" / "vibeloop-community.js").write_text(
        community_src.read_text(encoding="utf-8"), encoding="utf-8"
    )
    editor_src = Path(__file__).resolve().parent / "vibeloop_editor.js"
    (SITE_ROOT / "js" / "vibeloop-editor.js").write_text(editor_src.read_text(encoding="utf-8"), encoding="utf-8")
    sounds_src = Path(__file__).resolve().parent / "vibeloop_sounds.js"
    (SITE_ROOT / "js" / "vibeloop-sounds.js").write_text(sounds_src.read_text(encoding="utf-8"), encoding="utf-8")
    emoji_src = Path(__file__).resolve().parent / "vibeloop_emoji.js"
    (SITE_ROOT / "js" / "vibeloop-emoji.js").write_text(emoji_src.read_text(encoding="utf-8"), encoding="utf-8")
    live_src = Path(__file__).resolve().parent / "vibeloop_live.js"
    (SITE_ROOT / "js" / "vibeloop-live.js").write_text(live_src.read_text(encoding="utf-8"), encoding="utf-8")

    write_assets(SITE_ROOT, site_url=resolved_url)

    from jam.jami_cloudflare import copy_cloudflare_assets, ensure_d1_database, write_wrangler_toml
    from jam.jami_r2 import r2_available

    copy_cloudflare_assets(SITE_ROOT)
    try:
        db_id = ensure_d1_database()
        write_wrangler_toml(SITE_ROOT, db_id, use_r2=r2_available())
        ai_toml = SITE_ROOT / "wrangler.toml"
        if ai_toml.is_file() and "[ai]" not in ai_toml.read_text(encoding="utf-8"):
            ai_toml.write_text(
                ai_toml.read_text(encoding="utf-8").rstrip()
                + '\n\n[ai]\nbinding = "AI"\n',
                encoding="utf-8",
            )
    except Exception:
        pass

    return SITE_ROOT


def start_server(*, open_browser: bool = True) -> str:
    if not (SITE_ROOT / "index.html").is_file():
        build_site()
    handler = lambda *a, **k: SimpleHTTPRequestHandler(*a, directory=str(SITE_ROOT), **k)
    server = ThreadingHTTPServer(("127.0.0.1", SITE_PORT), handler)

    def run():
        server.serve_forever()

    threading.Thread(target=run, daemon=True).start()
    if open_browser:
        try:
            webbrowser.open(SITE_URL, new=2)
        except OSError:
            pass
    return SITE_URL


if __name__ == "__main__":
    build_site()
    print(f"Flarlo gebaut: {SITE_ROOT}")
    start_server()
