"""Build plain-JSON GitHub snapshots from a `wrangler d1 export` SQL dump.

Usage:
  python scripts/export_github_snapshot.py --dump pixify-db.sql --out data

Produces gallery.json, collections.json and media-index.json. Each file uses
the same `{ cachedAt, value }` envelope as the serving cache, so an offsite
fallback can be consumed without any transformation.
"""

import argparse
import json
import re
import sqlite3
import time
from pathlib import Path
from urllib.parse import quote, urlparse


def jsquote(value):
    return quote(str(value), safe="-_.!~*'()")


def parse_list(value):
    if isinstance(value, list):
        return value
    if isinstance(value, str):
        try:
            parsed = json.loads(value)
            if isinstance(parsed, list):
                return parsed
        except Exception:
            pass
    return []


def media_value(value):
    if not isinstance(value, str):
        return ""
    value = value.strip()
    if not value or value.lower().startswith("/api/media"):
        return ""
    return value if value.lower().startswith(("http://", "https://")) else ""


DIRECT_VIEWER_HOST = re.compile(
    r"(^|\.)(pixhost\.to|pixhost\.cc|pixhost\.st|pixho\.st|hostux\.pics)$", re.I
)


def direct_image_for_viewer(value):
    """Only hosts that allow browser hotlinking get a direct display URL."""
    value = media_value(value)
    if not value:
        return ""
    try:
        parsed = urlparse(value)
        return value if parsed.scheme in ("http", "https") and DIRECT_VIEWER_HOST.search(parsed.hostname or "") else ""
    except Exception:
        return ""


def build_gallery(conn):
    conn.row_factory = sqlite3.Row

    def rows(sql):
        return [dict(row) for row in conn.execute(sql).fetchall()]

    media_images = {}
    media_sources = {}
    for row in rows("SELECT artwork_id, image_url, source_url FROM pixify_media"):
        aid = str(row.get("artwork_id") or "")
        media_images[aid] = str(row.get("image_url") or "")
        media_sources[aid] = str(row.get("source_url") or "")

    collections = {}
    for row in rows("SELECT * FROM pixify_collections ORDER BY updated_at DESC"):
        col = {
            "id": row["id"],
            "name": row["name"],
            "description": row.get("description") or "",
            "artworkIds": [],
            "links": [],
            "groups": [],
            "updatedAt": row.get("updated_at"),
            "createdAt": row.get("created_at"),
        }
        if row.get("cover_id"):
            col["coverId"] = row["cover_id"]
        collections[str(row["id"])] = col

    artworks = []
    for row in rows("SELECT * FROM pixify_artworks ORDER BY created_at DESC"):
        aid = str(row["id"])
        direct = media_value(media_images.get(aid, ""))
        if direct:
            image = f"/api/media?url={jsquote(direct)}"
        elif aid in media_images or aid in media_sources:
            image = f"/api/media/{jsquote(aid)}"
        else:
            image = ""
        artist_id = row.get("artist_id") or str(row.get("artist") or "unknown").lower().replace(" ", "-")
        artworks.append({
            "id": row["id"],
            "title": row.get("title") or "Fanart",
            "artist": row.get("artist") or "Unknown Artist",
            "artistId": artist_id,
            "image": image,
            "directImage": direct_image_for_viewer(direct),
            "sourceUrl": media_sources.get(aid, ""),
            "width": int(row.get("width") or 1200),
            "height": int(row.get("height") or 1600),
            "tags": parse_list(row.get("tags")),
            "createdAt": row.get("created_at"),
            "updatedAt": row.get("updated_at"),
            "views": int(row.get("views") or 0),
            "bookmarks": int(row.get("bookmarks") or 0),
            "isNsfw": bool(row.get("is_nsfw")),
        })

    for row in rows("SELECT collection_id, artwork_id FROM pixify_collection_artworks ORDER BY position ASC"):
        col = collections.get(str(row.get("collection_id")))
        aid = str(row.get("artwork_id"))
        if col and aid not in col["artworkIds"]:
            col["artworkIds"].append(aid)

    for row in rows("SELECT * FROM pixify_collection_links ORDER BY added_at DESC"):
        col = collections.get(str(row.get("collection_id")))
        if col:
            col["links"].append({
                "id": row.get("id"),
                "url": row.get("url"),
                "title": row.get("title"),
                "note": row.get("note") or "",
                "addedAt": row.get("added_at"),
            })

    for row in rows("SELECT * FROM pixify_collection_groups ORDER BY updated_at DESC"):
        col = collections.get(str(row.get("collection_id")))
        if col:
            col["groups"].append({
                "id": row.get("id"),
                "collectionId": row.get("collection_id"),
                "name": row.get("name"),
                "description": row.get("description") or "",
                "artworkIds": [str(value) for value in parse_list(row.get("artwork_ids"))],
                "coverId": row.get("cover_id"),
                "createdAt": row.get("created_at"),
                "updatedAt": row.get("updated_at"),
            })

    return {"collections": list(collections.values()), "artworks": artworks}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--dump", required=True, help="Path to a `wrangler d1 export` SQL file")
    parser.add_argument("--out", default="data", help="Output directory")
    args = parser.parse_args()

    conn = sqlite3.connect(":memory:")
    conn.executescript(Path(args.dump).read_text(encoding="utf-8"))
    gallery = build_gallery(conn)

    collections = []
    for col in gallery["collections"]:
        meta = {key: value for key, value in col.items()
                if key not in ("artworkIds", "links", "groups")}
        meta["count"] = len(col["artworkIds"])
        meta["linkCount"] = len(col["links"])
        meta["groupCount"] = len(col["groups"])
        collections.append(meta)

    source_counts = {}
    for art in gallery["artworks"]:
        source = media_value(art.get("sourceUrl"))
        if source:
            source_counts[source] = source_counts.get(source, 0) + 1
    source_pairs = [[url, count] for url, count in source_counts.items()]

    cached_at = int(time.time() * 1000)
    payloads = {
        "gallery.json": gallery,
        "collections.json": {"collections": collections, "artworkCount": len(gallery["artworks"])},
        "media-index.json": {
            "sources": source_pairs,
            "total": sum(count for _, count in source_pairs),
        },
    }

    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    for name, value in payloads.items():
        target = out / name
        target.write_text(
            json.dumps({"cachedAt": cached_at, "value": value}, ensure_ascii=False, separators=(",", ":")),
            encoding="utf-8",
        )
        print(name, target.stat().st_size)
    print("artworks", len(gallery["artworks"]), "collections", len(collections), "sources", len(source_pairs))


if __name__ == "__main__":
    main()
