#!/usr/bin/env python3
import argparse
import shutil

from script_common import dotnet_env, find_csproj_by_keyword, resolve_repo_root, run


def main() -> int:
    parser = argparse.ArgumentParser(description="Cross-platform ASP.NET gateway publish helper")
    parser.add_argument("--configuration", choices=["Release", "Debug"], default="Release")
    parser.add_argument("--runtime", default="win-x64")
    parser.add_argument("--self-contained", action="store_true")
    parser.add_argument("--skip-web-assets", action="store_true")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--project", default=None, help="Relative/absolute path to gateway csproj")
    parser.add_argument("--web-build-dir", default=None, help="Relative path to web build assets root")
    parser.add_argument("--output-dir", default="output/webgateway")
    args = parser.parse_args()

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

    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 web gateway project. Pass --project <path/to/project.csproj>.")
        return 2

    publish_args = [
        "publish",
        str(csproj),
        "-c",
        args.configuration,
        "-r",
        args.runtime,
        "--self-contained",
        "true" if args.self_contained else "false",
        "-p:RestoreIgnoreFailedSources=true",
        "-p:NuGetAudit=false",
        "-o",
        str(output_dir),
    ]
    code = run("dotnet", publish_args, repo_root, env=dotnet_env(repo_root))
    if code != 0:
        return code

    if not args.skip_web_assets:
        if args.web_build_dir:
            web_build_dir = (repo_root / args.web_build_dir).resolve()
        else:
            web_build_dir = next((p.parent for p in repo_root.rglob("package.json") if (p.parent / "build").exists()), None)
            if web_build_dir is not None:
                web_build_dir = web_build_dir / "build"

        if web_build_dir is None or not web_build_dir.exists():
            print("Web assets not found. Skip with --skip-web-assets or pass --web-build-dir.")
        else:
            web_out = output_dir / "wwwroot"
            web_out.mkdir(parents=True, exist_ok=True)
            for item in web_build_dir.iterdir():
                dst = web_out / item.name
                if item.is_dir():
                    if dst.exists():
                        shutil.rmtree(dst)
                    shutil.copytree(item, dst)
                else:
                    shutil.copy2(item, dst)
            print(f"Copied web assets: {web_out}")

    print(f"Publish completed: {output_dir}")
    return 0


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