#!/usr/bin/env python3
"""
scripts/import_games.py
Oyun JSON veya CSV dosyasını playhop.gg'ye import eder.

Kullanım:
  python import_games.py --file games.json
  python import_games.py --file games.csv --format csv

JSON format: [{"title":"..","embed_url":"..","category":"action","thumbnail":".."}]
CSV başlık:  title,embed_url,category,thumbnail,description,platform
"""

import json
import csv
import re
import sys
import argparse
import mysql.connector
from pathlib import Path

# ────────────────────────────────────────────────────────────
DB_CONFIG = {
    "host":     "localhost",
    "database": "playhop_db",
    "user":     "playhop_user",
    "password": "GUCLU_SIFRE_BURAYA",
    "charset":  "utf8mb4",
}
# ────────────────────────────────────────────────────────────


def slugify(text: str) -> str:
    text = text.lower().strip()
    text = re.sub(r"[ğ]", "g", text)
    text = re.sub(r"[ü]", "u", text)
    text = re.sub(r"[ş]", "s", text)
    text = re.sub(r"[ı]", "i", text)
    text = re.sub(r"[ö]", "o", text)
    text = re.sub(r"[ç]", "c", text)
    text = re.sub(r"[^a-z0-9\s-]", "", text)
    text = re.sub(r"[\s-]+", "-", text)
    return text.strip("-")


def load_games(filepath: str, fmt: str) -> list[dict]:
    path = Path(filepath)
    if not path.exists():
        print(f"Hata: {filepath} bulunamadı.")
        sys.exit(1)

    if fmt == "json":
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    else:  # csv
        games = []
        with open(path, newline="", encoding="utf-8") as f:
            reader = csv.DictReader(f)
            for row in reader:
                games.append(dict(row))
        return games


def main():
    parser = argparse.ArgumentParser(description="PlayHop oyun import aracı")
    parser.add_argument("--file",   required=True, help="Import edilecek dosya")
    parser.add_argument("--format", default="json", choices=["json", "csv"])
    parser.add_argument("--dry-run", action="store_true", help="Kaydetmeden test et")
    args = parser.parse_args()

    games = load_games(args.file, args.format)
    print(f"Yüklendi: {len(games)} oyun")

    if args.dry_run:
        print("DRY-RUN modu — veritabanına yazılmıyor.")
        for g in games[:3]:
            print(f"  Örnek: {g.get('title')} → slug: {slugify(g.get('title',''))}")
        return

    conn   = mysql.connector.connect(**DB_CONFIG)
    cursor = conn.cursor(dictionary=True)

    # Kategori slug → id haritası
    cursor.execute("SELECT id, slug FROM categories")
    cat_map = {row["slug"]: row["id"] for row in cursor.fetchall()}

    inserted = 0
    skipped  = 0

    for item in games:
        title     = (item.get("title") or "").strip()
        embed_url = (item.get("embed_url") or "").strip()
        if not title or not embed_url:
            skipped += 1
            continue

        slug = slugify(title)
        # Var mı?
        cursor.execute("SELECT id FROM games WHERE slug = %s", (slug,))
        if cursor.fetchone():
            skipped += 1
            continue

        cat_slug    = (item.get("category") or "").strip()
        category_id = cat_map.get(cat_slug)

        cursor.execute("""
            INSERT INTO games
              (slug, title, description, embed_url, thumbnail, category_id, platform, status)
            VALUES (%s, %s, %s, %s, %s, %s, %s, 'active')
        """, (
            slug,
            title,
            (item.get("description") or "").strip() or None,
            embed_url,
            (item.get("thumbnail") or "").strip() or None,
            category_id,
            (item.get("platform") or "desktop,mobile").strip(),
        ))
        inserted += 1

        if inserted % 50 == 0:
            conn.commit()
            print(f"  → {inserted} eklendi...")

    conn.commit()
    cursor.close()
    conn.close()

    print(f"\nTamamlandı: {inserted} eklendi, {skipped} atlandı.")


if __name__ == "__main__":
    main()
