#!/usr/bin/env python3
"""Prepare local mods, tar them, generate config, and commit."""

import os
import subprocess
import sys

BASE = os.path.dirname(os.path.abspath(__file__))
PREPARE_LOCAL = os.path.join(BASE, "prepare_local")
AUTOGEN = os.path.join(BASE, "scripts", "autogen_config.py")
LOCALMODS_DIR = os.path.join(BASE, "LocalMods")
TAR_PATH = os.path.join(BASE, "LocalMods.tar.gz")


def log_ok(msg):
    print(f"\033[92m✓\033[0m {msg}")

def log_info(msg):
    print(f"• {msg}")

def log_err(msg):
    print(f"\033[91m✗\033[0m {msg}", file=sys.stderr)


def main():
    msg = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "Update LocalMods"

    print()
    print("╔════════════════════════════════════╗")
    print("║        Prep: mods → tar → commit  ║")
    print("╚════════════════════════════════════╝")
    print()

    log_info("Step 1/4: Copy mods from workshop...")
    subprocess.run([sys.executable, PREPARE_LOCAL], check=True)
    log_ok("LocalMods ready")
    print()

    log_info("Step 2/4: Taring LocalMods/...")
    if os.path.exists(TAR_PATH):
        os.remove(TAR_PATH)
    subprocess.run(["tar", "-czf", TAR_PATH, "-C", BASE, "LocalMods"], check=True)
    size = os.path.getsize(TAR_PATH)
    log_ok(f"Created {TAR_PATH} ({size / 1024:.1f} KB)")
    print()

    log_info("Step 3/4: Generating config_player.xml...")
    subprocess.run([sys.executable, AUTOGEN], check=True)
    log_ok("config_player.xml generated")
    print()

    log_info("Step 4/4: Committing...")
    subprocess.run(["git", "add", "-A"], cwd=BASE, check=True)
    subprocess.run(["git", "commit", "-m", msg], cwd=BASE, check=True)
    log_ok(f"Committed: {msg}")
    print()

    log_ok("Done. Push manually when ready.")


if __name__ == "__main__":
    main()
