from __future__ import annotations

"""Read-only production database health check."""
import json
from pathlib import Path
from config import Settings
from database import Database

def main() -> None:
    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 doctor_mysql.py")
    expected = json.loads(Path(__file__).with_name("images_seed.json").read_text(encoding="utf-8"))
    expected_map = {str(item["key"]): str(item["file_id"]) for item in expected}
    db = Database(settings)
    countries = db.rows("SELECT name,code_hash FROM countries ORDER BY name")
    actual_map = {row["key"]: row["file_id"] for row in db.rows("SELECT `key`,file_id FROM images")}
    missing = sorted(set(expected_map) - set(actual_map))
    customized = sorted(key for key, value in expected_map.items() if key in actual_map and actual_map[key] != value)
    passwords = sum(row["code_hash"] is not None for row in countries)
    print(f"connection=OK engine={db.engine} countries={len(countries)} passwords_set={passwords}")
    print(f"images={len(actual_map)} seed_images={len(expected_map)} missing={len(missing)} customized={len(customized)}")
    if len(countries) != 44 or missing:
        raise SystemExit("Database validation failed. Run python bootstrap_mysql.py and check again.")
    print("health=OK")

if __name__ == "__main__":
    main()
