import argparse
import sys

from nebula_cert_manager.exceptions import (
    CertManagerError,
    CertNotFoundError,
    RegistryNotFoundError,
)
from nebula_cert_manager.registry import RegistryManager


def add_parser(subparsers: argparse._SubParsersAction) -> None:
    parser = subparsers.add_parser(
        "delete", help="Delete a certificate record from the registry"
    )
    parser.add_argument("--fingerprint", required=True, help="Certificate fingerprint")
    parser.set_defaults(func=run)


def delete_cert(
    registry_mgr: RegistryManager,
    fingerprint: str,
) -> tuple[str, str]:
    """Delete a certificate record from the registry.

    Returns (name, fingerprint) of the deleted certificate.
    Raises RegistryNotFoundError, CertNotFoundError.
    """
    if not registry_mgr.exists():
        raise RegistryNotFoundError()

    registry = registry_mgr.load()

    result = registry.find_by_fingerprint(fingerprint)
    if result is None:
        raise CertNotFoundError(fingerprint=fingerprint)

    name, client = result
    registry.clients[name].remove(client)

    if not registry.clients[name]:
        del registry.clients[name]

    registry_mgr.save(registry)
    return (name, fingerprint)


def run(args: argparse.Namespace) -> None:
    try:
        name, fingerprint = delete_cert(args.registry_mgr, args.fingerprint)
    except CertManagerError as e:
        print(f"Error: {e}", file=sys.stderr)
        sys.exit(1)
    print(f"Certificate deleted: {name} (fingerprint: {fingerprint})")
