from __future__ import annotations

import configparser
import shutil
import time
from pathlib import Path
from typing import Any

from .paths import EnvironmentPaths


def verify_moza_ac_plugin(paths: EnvironmentPaths) -> dict[str, Any]:
    if paths.assetto_root is None:
        raise RuntimeError("Assetto Corsa install was not found")
    ac_python_root = paths.assetto_root / "apps" / "python"
    moza_candidates = [path for path in ac_python_root.iterdir() if path.is_dir() and path.name.lower() == "moza"] if ac_python_root.exists() else []
    python_ini = paths.cfg_root / "python.ini"
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if python_ini.exists():
        parser.read(python_ini, encoding="utf-8")
    enabled = None
    for section in parser.sections():
        if section.lower() == "moza":
            enabled = parser.get(section, "ACTIVE", fallback=None)
            break
    return {
        "installed": bool(moza_candidates),
        "paths": [str(path) for path in moza_candidates],
        "python_ini_enabled": enabled,
        "pit_house_source": str(Path(r"C:\Program Files (x86)\MOZA Pit House\bin\GameConfigs\Assetto Corsa\Moza")),
        "notes": [
            "Official MOZA docs say the AC app should live under assettocorsa\\apps\\python\\Moza and be enabled in AC Python modules."
        ],
    }


def install_moza_ac_plugin(paths: EnvironmentPaths, *, enable: bool = True) -> dict[str, Any]:
    if paths.assetto_root is None:
        raise RuntimeError("Assetto Corsa install was not found")
    source_root = Path(r"C:\Program Files (x86)\MOZA Pit House\bin\GameConfigs\Assetto Corsa\Moza")
    if not source_root.exists():
        raise RuntimeError("MOZA AC plugin payload was not found in Pit House install")
    target_root = paths.assetto_root / "apps" / "python" / "Moza"
    backup_path = None
    if target_root.exists():
        backup_path = paths.runtime_root / f"moza_app.backup.{time.strftime('%Y%m%d-%H%M%S')}"
        backup_path.parent.mkdir(parents=True, exist_ok=True)
        shutil.copytree(target_root, backup_path, dirs_exist_ok=True)
        shutil.rmtree(target_root)
    shutil.copytree(source_root, target_root)

    python_ini = paths.cfg_root / "python.ini"
    parser = configparser.ConfigParser()
    parser.optionxform = str
    if python_ini.exists():
        parser.read(python_ini, encoding="utf-8")
    if not parser.has_section("MOZA"):
        parser.add_section("MOZA")
    parser.set("MOZA", "ACTIVE", "1" if enable else "0")
    with python_ini.open("w", encoding="utf-8") as handle:
        parser.write(handle, space_around_delimiters=False)

    return {
        "source_root": str(source_root),
        "target_root": str(target_root),
        "backup_path": str(backup_path) if backup_path else None,
        "python_ini": str(python_ini),
        "enabled": enable,
    }
