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

from script_common import dotnet_env, find_csproj_by_keyword, resolve_repo_root, run


def main() -> int:
    parser = argparse.ArgumentParser(description="Cross-platform .NET sidecar publish helper")
    parser.add_argument("--configuration", default="Release")
    parser.add_argument("--runtime", default="win-x64")
    parser.add_argument("--repo-root", default=None)
    parser.add_argument("--project", default=None, help="Relative/absolute path to sidecar csproj")
    parser.add_argument("--output-dir", default="output")
    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, ["sidecar"])
    if csproj is None or not csproj.exists():
        print("Could not locate sidecar project. Pass --project <path/to/project.csproj>.")
        return 2

    publish_args = [
        "publish",
        str(csproj),
        "-c",
        args.configuration,
        "-r",
        args.runtime,
        "--self-contained",
        "-p:PublishSingleFile=true",
        "-p:IncludeNativeLibrariesForSelfExtract=true",
        "-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

    binary_name = csproj.stem + (".exe" if args.runtime.startswith("win-") else "")
    binary_path = output_dir / binary_name
    if binary_path.exists():
        print(f"Published executable: {binary_path}")
    else:
        print(f"Publish completed. Output directory: {output_dir}")
    return 0


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