#!/usr/bin/env python3
import argparse
import shutil
import subprocess
import sys
from pathlib import Path

from script_common import find_node_app_root, resolve_repo_root


def run_step(label: str, cmd: list[str], cwd: Path, dry_run: bool) -> int:
    print(f"\n> {label}")
    print("$", " ".join(cmd))
    if dry_run:
        return 0
    proc = subprocess.run(cmd, cwd=str(cwd), check=False)
    return proc.returncode


def main() -> int:
    parser = argparse.ArgumentParser(description="Publish bundled outputs using Python script entrypoints")
    parser.add_argument("--configuration", choices=["Release", "Debug"], default="Release")
    parser.add_argument("--runtime", default="win-x64")
    parser.add_argument("--skip-sidecar", action="store_true")
    parser.add_argument("--skip-web", action="store_true")
    parser.add_argument("--skip-webgateway", action="store_true")
    parser.add_argument("--skip-tauri", action="store_true")
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--sidecar-project", default=None)
    parser.add_argument("--gateway-project", default=None)
    parser.add_argument("--app-root", default=None)
    parser.add_argument("--output-dir", default="output")
    args = parser.parse_args()

    repo_root = resolve_repo_root(args.repo_root)
    output_root = (repo_root / args.output_dir).resolve()
    output_root.mkdir(parents=True, exist_ok=True)

    py = sys.executable
    if not args.skip_sidecar:
        cmd = [py, "scripts/publish-sidecar.py", "--configuration", args.configuration, "--runtime", args.runtime]
        if args.sidecar_project:
            cmd.extend(["--project", args.sidecar_project])
        code = run_step("Publish sidecar", cmd, repo_root, args.dry_run)
        if code != 0:
            return code

    if not args.skip_web:
        cmd = [py, "scripts/publish-app.py", "--target", "web", "--configuration", args.configuration]
        if args.app_root:
            cmd.extend(["--app-root", args.app_root])
        code = run_step("Build web", cmd, repo_root, args.dry_run)
        if code != 0:
            return code

    if not args.skip_webgateway:
        cmd = [py, "scripts/publish-webgateway.py", "--configuration", args.configuration, "--runtime", args.runtime]
        if args.gateway_project:
            cmd.extend(["--project", args.gateway_project])
        code = run_step("Publish web gateway", cmd, repo_root, args.dry_run)
        if code != 0:
            return code

    if not args.skip_tauri:
        cmd = [py, "scripts/publish-app.py", "--target", "tauri", "--configuration", args.configuration, "--tauri-bundles", "none"]
        if args.app_root:
            cmd.extend(["--app-root", args.app_root])
        code = run_step("Build tauri", cmd, repo_root, args.dry_run)
        if code != 0:
            return code

        app_root = find_node_app_root(repo_root, args.app_root)
        if app_root is not None:
            target_dir = app_root / "src-tauri" / "target" / ("debug" if args.configuration == "Debug" else "release")
            exes = sorted(target_dir.glob("*.exe"), key=lambda p: p.stat().st_mtime, reverse=True)
            if exes:
                staged = output_root / exes[0].name
                if args.dry_run:
                    print(f"Would copy: {exes[0]} -> {staged}")
                else:
                    shutil.copy2(exes[0], staged)
                    print(f"Staged desktop executable: {staged}")

    print("\nPublish output workflow complete.")
    return 0


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