"""
ID Wispera Admin Passport Module
Encrypted storage and retrieval of provisioning provider admin keys.

Admin keys are stored as vault passports with special tags:
  - 'admin'
  - 'admin:<provider>'
  - 'provisioning'

The credential value is the JSON-serialised ProviderAuth dict.
"""

import json
from typing import Any, Optional

from id_wispera.types import Passport, CreatePassportInput
from id_wispera.vault import Vault
from id_wispera.passport import create_passport, list_passports, revoke_passport

# ──────────────────────────────────────────────────────────────────────────────
# Constants
# ──────────────────────────────────────────────────────────────────────────────

ADMIN_TAG = "admin"
PROVISIONING_TAG = "provisioning"


def _provider_tag(provider: str) -> str:
    return f"admin:{provider}"


# ──────────────────────────────────────────────────────────────────────────────
# CRUD
# ──────────────────────────────────────────────────────────────────────────────


def create_admin_passport(
    vault: Vault,
    provider: str,
    auth: dict[str, Any],
    human_owner: str,
) -> Passport:
    """
    Store a provider's admin credentials as a vault passport.

    The ``auth`` dict is serialised to JSON and stored as the passport's
    ``credentialValue``.
    """
    return create_passport(
        vault,
        CreatePassportInput(
            name=f"Admin — {provider}",
            credentialType="api-key",
            credentialValue=json.dumps(auth),
            visaType="privilege",
            platforms=["custom"],
            scope=["admin", "provisioning"],
            humanOwner=human_owner,
            tags=[ADMIN_TAG, _provider_tag(provider), PROVISIONING_TAG],
            notes=(
                f"Admin credentials for {provider} provisioning provider. "
                "Managed by id.wispera — do not edit manually."
            ),
        ),
    )


def find_admin_passport(
    vault: Vault,
    provider: str,
) -> Optional[Passport]:
    """
    Find the active admin passport for a given provider.
    Returns None if none exists.
    """
    tag = _provider_tag(provider)
    for p in list_passports(vault):
        if ADMIN_TAG in p.tags and tag in p.tags and p.status in ("active", "expiring"):
            return p
    return None


def get_provider_auth(
    vault: Vault,
    provider: str,
) -> dict[str, Any]:
    """
    Retrieve and deserialise the ProviderAuth for a given provider.

    Raises:
        ValueError: If no admin passport exists for the provider.
    """
    passport = find_admin_passport(vault, provider)
    if passport is None:
        raise ValueError(
            f"No admin credentials found for provider '{provider}'. "
            f"Run 'idw auth bootstrap {provider}' to store admin credentials."
        )
    return json.loads(passport.credential_value)


def list_admin_passports(vault: Vault) -> list[Passport]:
    """List all admin passports in the vault."""
    return [
        p
        for p in list_passports(vault)
        if ADMIN_TAG in p.tags and PROVISIONING_TAG in p.tags
    ]


def delete_admin_passport(vault: Vault, provider: str) -> bool:
    """
    Revoke and delete the admin passport for a provider.
    Returns True if an entry was removed.
    """
    passport = find_admin_passport(vault, provider)
    if passport is None:
        return False
    revoke_passport(vault, passport.id, actor="system", reason="Admin credential removed")
    vault.delete_passport(passport.id)
    return True
