"""Cloudflare R2 – Foto-Speicher für Jami-Dating."""

from __future__ import annotations

import re
import shutil
import subprocess
from pathlib import Path

from jam.jami_cloudflare import CF_SRC, _npx_base, _run

R2_BUCKET = "jami-photos"
R2_BINDING = "PHOTOS"


def r2_available() -> bool:
    code, out = _run(_npx_base() + ["r2", "bucket", "list"], CF_SRC.parent)
    if code != 0:
        return False
    if R2_BUCKET in out:
        return True
    code, create_out = _run(_npx_base() + ["r2", "bucket", "create", R2_BUCKET], CF_SRC.parent)
    combined = create_out + out
    if code == 0 or "already exists" in combined.lower():
        return True
    if "enable R2" in combined or "10042" in combined:
        return False
    return False


def ensure_r2_bucket() -> tuple[bool, str]:
    if r2_available():
        return True, f"R2 Bucket '{R2_BUCKET}' bereit"
    return False, (
        "R2 noch nicht aktiv – einmal im Cloudflare Dashboard unter "
        "R2 → Overview → Enable R2 aktivieren, dann erneut deployen."
    )


def wrangler_r2_snippet() -> str:
    return f"""
[[r2_buckets]]
binding = "{R2_BINDING}"
bucket_name = "{R2_BUCKET}"
"""


def patch_wrangler_toml(path: Path) -> None:
    text = path.read_text(encoding="utf-8") if path.is_file() else ""
    if "r2_buckets" in text:
        return
    path.write_text(text.rstrip() + wrangler_r2_snippet(), encoding="utf-8")
