"""Stripe-Setup-Dateien für Jami."""

from __future__ import annotations

import json
import shutil
from pathlib import Path

STRIPE_CONFIG_EXAMPLE = {
    "enabled": False,
    "publishableKey": "pk_test_...",
    "priceIds": {
        "starter": "price_...",
        "plus": "price_...",
        "pro": "price_...",
        "vip": "price_...",
    },
    "note": "Cloudflare: STRIPE_SECRET_KEY + STRIPE_WEBHOOK_SECRET als Pages Secrets. Price-IDs aus dem Stripe-Dashboard.",
}

SETUP_TXT = """JAMI – Stripe (Karte + SEPA)
================================

Standard (Cloudflare D1): API unter /api/create-checkout-session und /api/stripe-webhook
Details: cloudflare/STRIPE_SETUP.md

1) Stripe-Konto: https://dashboard.stripe.com/register

2) Produkte/Preise anlegen → Price-IDs in js/stripe-config.json "priceIds"

3) API-Keys
   - Publishable → js/stripe-config.json
   - Secret → Cloudflare Pages Secret STRIPE_SECRET_KEY (nie ins Frontend!)

4) Cloudflare Pages Secrets
   STRIPE_SECRET_KEY=sk_test_...
   STRIPE_WEBHOOK_SECRET=whsec_...
   JAMI_SITE_URL=https://jami-9g3.pages.dev

5) Webhook-URL: https://DEINE-DOMAIN.pages.dev/api/stripe-webhook
   Event: checkout.session.completed

6) D1: migrate_stripe.sql ausführen (siehe STRIPE_SETUP.md)

7) cloudflare/: npm install  →  deploy

8) js/stripe-config.json → "enabled": true

9) Test: Coins-Shop → „Jetzt freischalten“ · Karte 4242 4242 4242 4242

Optional Supabase: supabase/functions/create-checkout + stripe-webhook (Legacy).
"""


def write_stripe_files(site_root: Path, repo_root: Path | None = None) -> None:
    site_root.mkdir(parents=True, exist_ok=True)
    root = repo_root or Path(__file__).resolve().parents[1]

    cfg = site_root / "js" / "stripe-config.json"
    local_cfg = root / "data" / "stripe-config.json"
    if local_cfg.is_file():
        shutil.copy2(local_cfg, cfg)
    elif not cfg.is_file():
        cfg.write_text(json.dumps(STRIPE_CONFIG_EXAMPLE, ensure_ascii=False, indent=2), encoding="utf-8")

    (site_root / "STRIPE_EINRICHTEN.txt").write_text(SETUP_TXT, encoding="utf-8")

    stripe_sql = root / "supabase" / "stripe_schema.sql"
    if stripe_sql.is_file():
        (site_root / "supabase").mkdir(exist_ok=True)
        shutil.copy2(stripe_sql, site_root / "supabase" / "stripe_schema.sql")

    func_src = root / "supabase" / "functions"
    if func_src.is_dir():
        dst = site_root / "supabase" / "functions"
        if dst.exists():
            shutil.rmtree(dst)
        shutil.copytree(func_src, dst)
