import argparse
import sys
from datetime import datetime, timezone
from pathlib import Path

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(
        "import-ca", help="Import existing CA into a new registry"
    )
    parser.add_argument(
        "--ca-cert", type=Path, required=True, help="Path to CA certificate file"
    )
    parser.add_argument(
        "--ca-key",
        required=True,
        help='Path to CA key file (use "-" for stdin)',
    )
    parser.set_defaults(func=run)


def import_ca_to_registry(
    registry_mgr: RegistryManager,
    pki: PKI,
    ca_cert_pem: str,
    ca_key_pem: str,
) -> Registry:
    """Import an existing CA into a new registry.

    Takes already-read cert/key content.
    Returns the created Registry.
    Raises RegistryExistsError.
    """
    if registry_mgr.exists():
        raise RegistryExistsError()

    cert_info = pki.print_cert(ca_cert_pem)
    fingerprint = cert_info.get("fingerprint", "")
    ca_name = cert_info.get("details", {}).get("name", "imported-ca")

    registry = Registry(
        ca=CAInfo(
            name=ca_name,
            cert=ca_cert_pem,
            key=ca_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 import-ca (or set NEBULA_CERT_MANAGER_AGE).",
            file=sys.stderr,
        )
        sys.exit(1)

    cert_pem = args.ca_cert.read_text()
    if args.ca_key == "-":
        key_pem = sys.stdin.read()
    else:
        key_pem = Path(args.ca_key).read_text()

    try:
        registry = import_ca_to_registry(args.registry_mgr, args.pki, cert_pem, key_pem)
    except CertManagerError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    print(f"Registry initialized with imported CA at {args.registry_mgr.registry_dir}")
    print(f"CA fingerprint: {registry.ca.fingerprint}")
