import argparse
import sys
from datetime import datetime, timezone

from nebula_cert_manager.exceptions import CertManagerError, RegistryExistsError
from nebula_cert_manager.models import CAInfo, Registry
from nebula_cert_manager.pki import PKI
from nebula_cert_manager.registry import RegistryManager


def add_parser(subparsers: argparse._SubParsersAction) -> None:
    parser = subparsers.add_parser(
        "init", help="Initialize registry and create a new CA"
    )
    parser.add_argument("--ca-name", default="nebula-ca", help="CA certificate name")
    parser.add_argument(
        "--duration", default=None, help="CA certificate duration (e.g., 8760h)"
    )
    parser.set_defaults(func=run)


def init_registry(
    registry_mgr: RegistryManager,
    pki: PKI,
    ca_name: str = "nebula-ca",
    duration: str | None = None,
) -> Registry:
    """Initialize a new registry and create a CA.

    Returns the created Registry.
    Raises RegistryExistsError.
    """
    if registry_mgr.exists():
        raise RegistryExistsError(
            "Registry already exists. Use 'import-ca' to import into existing registry."
        )

    cert_pem, key_pem = pki.create_ca(ca_name, duration)

    cert_info = pki.print_cert(cert_pem)
    fingerprint = cert_info.get("fingerprint", "")

    registry = Registry(
        ca=CAInfo(
            name=ca_name,
            cert=cert_pem,
            key=key_pem,
            fingerprint=fingerprint,
            created_at=datetime.now(timezone.utc),
        ),
        clients={},
    )

    registry_mgr.save(registry)
    return registry


def run(args: argparse.Namespace) -> None:
    if not args.age:
        print(
            "Error: --age is required for init (or set NEBULA_CERT_MANAGER_AGE).",
            file=sys.stderr,
        )
        sys.exit(1)

    print(f"Creating CA '{args.ca_name}'...")
    try:
        registry = init_registry(
            args.registry_mgr, args.pki, args.ca_name, args.duration
        )
    except CertManagerError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    print(f"Registry initialized at {args.registry_mgr.registry_dir}")
    print(f"CA fingerprint: {registry.ca.fingerprint}")
