#!/usr/bin/env python3
import argparse
import os
from pathlib import Path

from script_common import dotnet_env, find_csproj_by_keyword, resolve_repo_root, run


def main() -> int:
    parser = argparse.ArgumentParser(description="Run gateway in dev or output mode")
    parser.add_argument("--configuration", choices=["Release", "Debug"], default="Release")
    parser.add_argument("--urls", default="http://0.0.0.0:5180")
    parser.add_argument("--project-root", default=None, help="Runtime project root exposed via SDT_PROJECT_ROOT")
    parser.add_argument("--mode", choices=["Dev", "Output"], default="Dev")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--project", default=None, help="Gateway csproj path")
    parser.add_argument("--output-exe", default=None, help="Published gateway executable path")
    args = parser.parse_args()

    repo_root = resolve_repo_root(args.repo_root)
    effective_project_root = Path(args.project_root).resolve() if args.project_root else repo_root
    if not effective_project_root.exists():
        print(f"Project root does not exist: {effective_project_root}")
        return 2

    env = dotnet_env(repo_root)
    env["SDT_PROJECT_ROOT"] = str(effective_project_root)

    if args.mode == "Output":
        exe_path = Path(args.output_exe).resolve() if args.output_exe else (repo_root / "output" / "webgateway" / ("webgateway.exe" if os.name == "nt" else "webgateway"))
        if not exe_path.exists():
            print(f"Output executable not found: {exe_path}")
            return 2
        return run(str(exe_path), ["--urls", args.urls], repo_root, env=env)

    if args.project:
        csproj = (repo_root / args.project).resolve()
    else:
        csproj = find_csproj_by_keyword(repo_root, ["webgateway", "gateway"])
    if csproj is None or not csproj.exists():
        print("Could not locate gateway project. Pass --project <path/to/project.csproj>.")
        return 2

    run_args = [
        "run",
        "--project",
        str(csproj),
        "-c",
        args.configuration,
        "--no-launch-profile",
        "--urls",
        args.urls,
        "-p:RestoreIgnoreFailedSources=true",
        "-p:NuGetAudit=false",
    ]
    return run("dotnet", run_args, repo_root, env=env)


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