"""ptc infra register — register a cluster with PAM."""

import json
from pathlib import Path

import pydantic
import srsly
from pydantic import AnyUrl
from radicli import Arg
from wasabi import msg

from prodigy_teams_pam_sdk.errors import BrokerNotFound
from prodigy_teams_pam_sdk.models import BrokerCreating, BrokerUpdating

from ...cli import cli
from ...messages import Messages
from ...util import URL

CLOUD_PROVIDERS = ("gcp", "k3s", "aws")


@cli.subcommand(
    "infra",
    "register",
    name=Arg("--name", help="Human-readable name for the cluster"),
    domain=Arg(
        "--domain", help="Public FQDN of the cluster (e.g. cluster.example.com)"
    ),
    cloud_provider=Arg(
        "--cloud-provider",
        help=f"Cloud provider: {', '.join(CLOUD_PROVIDERS)}",
    ),
    as_json=Arg("--json", help=Messages.as_json),
)
def register(
    name: str,
    domain: str,
    cloud_provider: str,
    as_json: bool = False,
) -> None:
    """Register a new cluster with PAM and write credentials to cluster-creds.json."""
    from .._state import get_auth_state

    if cloud_provider not in CLOUD_PROVIDERS:
        msg.fail(
            f"Unknown cloud provider '{cloud_provider}'. "
            f"Choose from: {', '.join(CLOUD_PROVIDERS)}"
        )
        raise SystemExit(1)
    auth = get_auth_state()
    client = auth.client
    org_id = auth.org_id
    try:
        broker = client.broker.read(address=domain)
    except BrokerNotFound:
        body = BrokerCreating(
            name=name,
            org_id=org_id,
            address=pydantic.TypeAdapter(AnyUrl).validate_python(URL.parse(domain).url),
            cloud_provider=cloud_provider,
            public_key="",
            state="creating",
            cloud={},
        )
        broker = client.broker.create(body)
    else:
        update_body = BrokerUpdating(
            id=broker.id,
            name=name,
            address=domain,
            cloud_provider=cloud_provider,
            state="creating",
            cloud={},
        )
        _ = client.broker.update(update_body)
    creds = client.broker.credentials(broker_id=broker.id)
    creds_data = {
        "broker_id": str(creds.broker_id),
        "container_sa_key": creds.secrets.container_sa_key,
        "container_registry": creds.image.registry,
        "prodigy_license_key": creds.secrets.prodigy_license_key,
        "target_broker_version": creds.image.broker_version,
        "target_cpl_version": creds.image.cpl_version,
    }
    creds_path = Path("cluster-creds.json")
    srsly.write_json(creds_path, creds_data)
    if as_json:
        print(json.dumps(creds_data, indent=2))
    else:
        msg.good("Cluster registered with PAM")
        msg.info(f"  Broker ID:    {creds.broker_id}")
        msg.info(f"  Wrote credentials to {creds_path}")
