import argparse
import os
import sys
from pathlib import Path

from nebula_cert_manager.commands import (
    config,
    delete,
    import_ca,
    info,
    init,
    issue,
    list_cmd,
    revoke,
    sync,
)
from nebula_cert_manager.pki import PKI
from nebula_cert_manager.registry import RegistryManager
from nebula_cert_manager.sops import Sops


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="nebula-cert-manager",
        description="CLI tool for Nebula overlay network certificate lifecycle management",
    )
    parser.add_argument(
        "--registry-dir",
        type=Path,
        default=Path(os.environ.get("NEBULA_CERT_MANAGER_DIR", "./nebula-registry")),
        help="Registry directory (default: $NEBULA_CERT_MANAGER_DIR or ./nebula-registry)",
    )
    parser.add_argument(
        "--nebula-cert",
        default="nebula-cert",
        help="Path to nebula-cert binary (default: find in PATH)",
    )
    parser.add_argument(
        "--sops",
        default="sops",
        help="Path to sops binary (default: find in PATH)",
    )
    parser.add_argument(
        "--age",
        default=os.environ.get("NEBULA_CERT_MANAGER_AGE"),
        help="AGE public key for SOPS encryption (default: $NEBULA_CERT_MANAGER_AGE)",
    )

    subparsers = parser.add_subparsers(dest="command")

    init.add_parser(subparsers)
    import_ca.add_parser(subparsers)
    issue.add_parser(subparsers)
    revoke.add_parser(subparsers)
    delete.add_parser(subparsers)
    list_cmd.add_parser(subparsers)
    config.add_parser(subparsers)
    info.add_parser(subparsers)
    sync.add_parser(subparsers)

    return parser


def main(argv: list[str] | None = None) -> None:
    parser = build_parser()
    args = parser.parse_args(argv)

    if not args.command:
        parser.print_help()
        sys.exit(1)

    pki = PKI(args.nebula_cert)
    sops = Sops(args.sops, age_key=args.age)
    registry_mgr = RegistryManager(args.registry_dir, sops)

    args.pki = pki
    args.sops = sops
    args.registry_mgr = registry_mgr

    args.func(args)
