from pathlib import Path
import shutil
import sys

BASE_DIR = Path(__file__).resolve().parent
ENV_FILE = BASE_DIR / ".env.runtime"
ENV_BACKUP = BASE_DIR / ".env.runtime.server.backup"


def read_lines(path: Path):
    if not path.exists():
        return []
    return path.read_text(encoding="utf-8").splitlines()


def set_kv(lines, key, value):
    prefix = key + "="
    replaced = False
    new_lines = []

    for line in lines:
        stripped = line.strip()

        if stripped.startswith("#") or "=" not in stripped:
            new_lines.append(line)
            continue

        k = stripped.split("=", 1)[0].strip()

        if k == key:
            new_lines.append(f"{key}={value}")
            replaced = True
        else:
            new_lines.append(line)

    if not replaced:
        new_lines.append(f"{key}={value}")

    return new_lines


def main():
    print("[1/4] Checking project files...")

    required_files = [
        "app.py",
        "run_windows.py",
        "requirements-windows.txt",
        "firebase-service-account.json",
    ]

    missing = []

    for name in required_files:
        if not (BASE_DIR / name).exists():
            missing.append(name)

    if missing:
        print("Missing files:")
        for name in missing:
            print(" -", name)
        sys.exit(1)

    if not ENV_FILE.exists():
        ENV_FILE.write_text("", encoding="utf-8")

    if not ENV_BACKUP.exists():
        shutil.copy2(ENV_FILE, ENV_BACKUP)
        print("[2/4] Created backup:", ENV_BACKUP.name)
    else:
        print("[2/4] Backup already exists:", ENV_BACKUP.name)

    print("[3/4] Updating local .env.runtime...")

    lines = read_lines(ENV_FILE)

    lines = set_kv(lines, "SHOPPING_FIREBASE_SERVICE_ACCOUNT", "firebase-service-account.json")

    # Default mode: connect to remote SQL Server through SSH tunnel.
    # The tunnel maps local 127.0.0.1:1433 to server 127.0.0.1:1433.
    lines = set_kv(lines, "SHOPPING_DB_SERVER", "127.0.0.1,1433")
    lines = set_kv(lines, "SHOPPING_DB_DRIVER", "ODBC Driver 18 for SQL Server")

    ENV_FILE.write_text("\n".join(lines) + "\n", encoding="utf-8")

    print("[4/4] Local config is ready.")
    print()
    print("Next step:")
    print("Double click start_site.bat")
    print()


if __name__ == "__main__":
    main()