from __future__ import annotations

"""Create the new MySQL/MariaDB schema and import image mappings only.

The SQLite database supplied with the project is intentionally not imported
as a whole. This script imports only images_seed.json. Password hashes from
SQLite are never read or imported. Re-running it preserves passwords and any
images that were changed later through the admin panel.
"""

import argparse
import json
from pathlib import Path

from config import Settings
from database import Database


def main() -> None:
    parser = argparse.ArgumentParser(description="Bootstrap Empire MySQL database")
    parser.add_argument(
        "--seed",
        default=str(Path(__file__).with_name("images_seed.json")),
        help="JSON file containing image key/file_id mappings",
    )
    args = parser.parse_args()

    settings = Settings.from_env(require_bot=False)
    if settings.db_engine not in {"mysql", "mariadb"}:
        raise SystemExit("Set DB_ENGINE=mysql in .env before running bootstrap_mysql.py")

    seed_path = Path(args.seed)
    rows = json.loads(seed_path.read_text(encoding="utf-8"))
    if not isinstance(rows, list):
        raise SystemExit("Image seed must be a JSON list")
    mappings: list[tuple[str, str]] = []
    seen: set[str] = set()
    for item in rows:
        if not isinstance(item, dict) or not item.get("key") or not item.get("file_id"):
            raise SystemExit("Invalid image seed row")
        key, file_id = str(item["key"]), str(item["file_id"])
        if key in seen:
            raise SystemExit(f"Duplicate image key: {key}")
        seen.add(key)
        mappings.append((key, file_id))

    db = Database(settings)
    # Missing-only import makes this command safe to run again after the admin
    # has set new passwords or replaced images in Telegram.
    db.add_image_rows(mappings, overwrite=False)
    country_count = len(db.rows("SELECT id FROM countries"))
    password_count = len(db.rows("SELECT id FROM countries WHERE code_hash IS NOT NULL"))
    actual_keys = {row["key"] for row in db.rows("SELECT `key` FROM images")}
    missing = seen - actual_keys
    image_count = len(actual_keys)
    if country_count != 44 or missing:
        raise SystemExit(
            f"Validation failed: countries={country_count}, "
            f"passwords={password_count}, images={image_count}, missing_images={len(missing)}"
        )
    password_status = "empty (ready to set)" if password_count == 0 else f"preserved={password_count}"
    print(f"OK: schema ready; countries={country_count}; passwords {password_status}; images={image_count}")


if __name__ == "__main__":
    main()
