#!/usr/bin/env python3
from __future__ import annotations

import argparse
import sys
import subprocess
from pathlib import Path


def _run(cmd: list[str]) -> int:
    try:
        subprocess.run(cmd, check=True)
        return 0
    except subprocess.CalledProcessError as e:
        return int(e.returncode)


def main() -> int:
    ap = argparse.ArgumentParser(
        prog="serverrf",
        description="RemoteRF Server CLI (cert generation only)",
    )

    ap.add_argument(
        "--gen-certs",
        metavar="STATIC_IP",
        required=True,
        help="Generate TLS certs via ./tools/gen_certs.py and exit",
    )
    ap.add_argument(
        "--days",
        type=int,
        default=365,
        help="Server cert validity in days (default: 365)",
    )
    ap.add_argument(
        "--ca-days",
        type=int,
        default=3650,
        help="CA cert validity in days (default: 3650)",
    )
    ap.add_argument(
        "--bits",
        type=int,
        default=2048,
        help="RSA key size (default: 2048)",
    )
    ap.add_argument(
        "--dns",
        action="append",
        default=[],
        help="DNS SAN entry (repeatable)",
    )
    ap.add_argument(
        "--cn",
        default=None,
        help="Common Name (defaults to first SAN entry)",
    )
    ap.add_argument(
        "--force",
        action="store_true",
        help="Overwrite existing certs/keys",
    )
    ap.add_argument(
        "--config-dir",
        default=None,
        help="Base config dir (default: ~/.config/remoterf)",
    )
    ap.add_argument(
        "--out-subdir",
        default=None,
        help="Subdir under config dir (default: certs)",
    )
    ap.add_argument(
        "--no-detect-ip",
        action="store_true",
        help="Do not auto-detect IP when none provided",
    )

    args = ap.parse_args()

    # Resolve ./tools/gen_certs.py relative to this file (serverrf_cli.py)
    gen_path = (Path(__file__).resolve().parent / "tools" / "gen_certs.py").resolve()
    if not gen_path.exists():
        print(f"ERROR: cert generator not found: {gen_path}", file=sys.stderr)
        return 2

    cmd: list[str] = [
        sys.executable,
        str(gen_path),
        "--days", str(args.days),
        "--ca-days", str(args.ca_days),
        "--bits", str(args.bits),
    ]

    # STATIC_IP is required by this barebones CLI.
    # If you want "no arg means auto-detect", change argparse to nargs="?" and only append when provided.
    cmd += ["--ip", args.gen_certs]

    if args.force:
        cmd.append("--force")
    if args.no_detect_ip:
        cmd.append("--no-detect-ip")
    for d in args.dns:
        cmd += ["--dns", d]
    if args.cn:
        cmd += ["--cn", args.cn]
    if args.config_dir:
        cmd += ["--config-dir", args.config_dir]
    if args.out_subdir:
        cmd += ["--out-subdir", args.out_subdir]

    return _run(cmd)


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