"""ptc infra init-values — generate values.yaml from credentials."""

import secrets
from pathlib import Path
from typing import Any, Optional, Union

import srsly
from radicli import Arg
from wasabi import msg

from ...cli import cli

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


@cli.subcommand(
    "infra",
    "init-values",
    creds=Arg("--creds", help="Path to cluster-creds.json from 'infra register'"),
    cloud_provider=Arg(
        "--cloud-provider",
        help=f"Cloud provider: {', '.join(CLOUD_PROVIDERS)}",
    ),
    domain=Arg("--domain", help="Public FQDN of the cluster"),
    out=Arg("--out", help="Output path for generated values.yaml"),
    acme_email=Arg("--acme-email", help="Email for Let's Encrypt certificates"),
)
def init_values(
    creds: Path,
    cloud_provider: str,
    domain: str,
    out: Union[Path, str] = "values.yaml",
    acme_email: Optional[str] = None,
) -> None:
    """Generate a values.yaml for Helm deployment from credentials and provider defaults."""
    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)
    if isinstance(out, str):
        out = Path(out)
    creds_data = srsly.read_json(creds)
    assert isinstance(creds_data, dict)
    broker_id = creds_data["broker_id"]
    container_sa_key = creds_data.get("container_sa_key", "")
    container_registry = creds_data["container_registry"]
    if not container_registry:
        msg.fail(
            "container_registry in credentials is empty — PAM may be misconfigured."
        )
        raise SystemExit(1)
    prodigy_license_key = creds_data.get("prodigy_license_key", "")
    broker_version = creds_data.get("target_broker_version", "") or ""
    cpl_version = creds_data.get("target_cpl_version", "") or ""
    if not broker_version or not cpl_version:
        msg.warn(
            "Target versions not set by PAM. Set image tags manually in the "
            "generated values.yaml before deploying."
        )
    auth = get_auth_state()
    pam_fqdn = auth.pam_url.netloc
    values: dict[str, Any] = {
        "image": {
            "registry": container_registry,
            "brokerVersion": broker_version,
            "cplVersion": cpl_version,
        },
        "cluster": {
            "brokerId": broker_id,
            "fqdn": domain,
            "pamFqdn": pam_fqdn,
        },
    }
    if acme_email:
        values["ingress"] = {"tls": {"secretName": "prodigy-teams-tls"}}
        values["certManager"] = {"acmeEmail": acme_email}
    if cloud_provider == "k3s":
        values["broker"] = {"nodeSelector": {}}
        values["postgresql"] = {
            "enabled": True,
            "auth": {
                "database": "brokerdb",
                "username": "broker_user",
                "password": secrets.token_urlsafe(24),
            },
        }
        values["storage"] = {"type": "hostPath", "hostPath": "/srv/prodigy-data"}
        values["imagePullSecrets"] = [{"name": "explosion-registry"}]
        values["secrets"] = {
            "infraSecretName": "prodigy-teams-infra",
            "containerSaKey": container_sa_key,
            "prodigyLicenseKey": prodigy_license_key,
        }
    elif cloud_provider == "gcp":
        values["gcp"] = {"project": "your-gcp-project", "zone": "europe-west1-d"}
        values["serviceAccount"] = {
            "annotations": {
                "iam.gke.io/gcp-service-account": "cluster-gke-sa@your-project.iam.gserviceaccount.com",
            },
        }
        values["database"] = {
            "ip": "FILL-IN",
            "user": "broker_user",
            "name": "brokerdb",
        }
        values["secrets"] = {
            "infraSecretName": "prodigy-teams-infra",
            "containerSaKey": container_sa_key,
            "prodigyLicenseKey": prodigy_license_key,
        }
        values["nfs"] = {"claimName": "prodigy-nfs"}
    elif cloud_provider == "aws":
        values["database"] = {
            "ip": "FILL-IN",
            "user": "broker_user",
            "name": "brokerdb",
        }
        values["imagePullSecrets"] = [{"name": "explosion-registry"}]
        values["secrets"] = {
            "infraSecretName": "prodigy-teams-infra",
            "containerSaKey": container_sa_key,
            "prodigyLicenseKey": prodigy_license_key,
        }
        values["nfs"] = {"claimName": "prodigy-nfs"}
    srsly.write_yaml(out, values)
    msg.good(f"Generated {out}")
    msg.info(
        f"  Review and edit before deploying with 'ptc infra deploy --values {out}'"
    )
