from __future__ import annotations

import argparse
import shutil
import subprocess
import sys
from pathlib import Path


PROJECT_DIR = Path(__file__).resolve().parent.parent
SETTINGS_DIR = PROJECT_DIR / "settings"
DEFAULT_WINDOWS_LOCAL_ROOT = Path(r"D:\Hermes\local")

EXAMPLE_SETTINGS = {
    "auth_settings.example.json": "auth_settings.json",
    "download_tech_pack_settings.example.json": "download_tech_pack_settings.json",
    "server_settings.example.json": "server_settings.json",
    "ui_state.example.json": "ui_state.json",
}


def copy_example_settings(*, force: bool) -> list[Path]:
    copied: list[Path] = []
    for example_name, target_name in EXAMPLE_SETTINGS.items():
        source = SETTINGS_DIR / example_name
        target = SETTINGS_DIR / target_name
        if not source.exists():
            continue
        if target.exists() and not force:
            continue
        shutil.copy2(source, target)
        copied.append(target)
    return copied


def ensure_local_runtime_dirs() -> list[Path]:
    created: list[Path] = []
    for path in (
        DEFAULT_WINDOWS_LOCAL_ROOT,
        DEFAULT_WINDOWS_LOCAL_ROOT / "data",
        DEFAULT_WINDOWS_LOCAL_ROOT / "debug",
        DEFAULT_WINDOWS_LOCAL_ROOT / "shared",
        DEFAULT_WINDOWS_LOCAL_ROOT / "mail_outbox",
    ):
        path.mkdir(parents=True, exist_ok=True)
        created.append(path)
    return created


def ensure_virtualenv(*, reinstall_requirements: bool) -> None:
    venv_python = PROJECT_DIR / ".venv" / "Scripts" / "python.exe"
    if not venv_python.exists():
        subprocess.run([sys.executable, "-m", "venv", str(PROJECT_DIR / ".venv")], cwd=PROJECT_DIR, check=True)
    if reinstall_requirements:
        subprocess.run(
            [str(venv_python), "-m", "pip", "install", "-r", "requirements.txt"],
            cwd=PROJECT_DIR,
            check=True,
        )


def main() -> int:
    parser = argparse.ArgumentParser(description="Bootstrap a clean CitiFox ERP development machine.")
    parser.add_argument("--force-settings", action="store_true", help="Overwrite runtime settings from *.example.json files.")
    parser.add_argument("--skip-venv", action="store_true", help="Do not create or update .venv.")
    parser.add_argument("--skip-pip", action="store_true", help="Do not install requirements into .venv.")
    args = parser.parse_args()

    copied = copy_example_settings(force=args.force_settings)
    dirs = ensure_local_runtime_dirs()

    if not args.skip_venv:
        ensure_virtualenv(reinstall_requirements=not args.skip_pip)

    print("Bootstrap completed.")
    print("")
    print("Settings synced from examples:")
    for path in copied:
        print(f"- {path}")
    if not copied:
        print("- No settings file needed to be copied.")
    print("")
    print("Local runtime folders ensured:")
    for path in dirs:
        print(f"- {path}")
    print("")
    print("Next steps:")
    print("- Review settings/server_settings.json on this machine if you need a different server mode.")
    print("- Run scripts\\run_app.bat to open the desktop app.")
    print("- Runtime login, UI state, and tech pack credentials stay local to this machine.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
