"""Resolve and validate the public config into an internal, ready-to-use form."""

from __future__ import annotations

from dataclasses import dataclass
from urllib.parse import urljoin

from .types import JwksOptions, PartnerEcosystemConfig


@dataclass
class ResolvedConfig:
    """Fully-resolved, validated configuration used internally by the client."""

    api_url: str
    project_id: str
    project_secret: str
    jwks_uri: str
    audience: str
    jwks: JwksOptions
    issuer: "str | None" = None


def resolve_config(config: PartnerEcosystemConfig) -> ResolvedConfig:
    api_url = _require_string(config.api_url, "api_url")
    project_id = _require_string(config.project_id, "project_id")
    project_secret = _require_string(config.project_secret, "project_secret")

    base = api_url.rstrip("/")
    jwks_path = config.jwks_path or "/.well-known/jwks.json"

    try:
        jwks_uri = urljoin(base + "/", jwks_path.lstrip("/"))
    except ValueError as exc:  # pragma: no cover - urljoin rarely raises
        raise ValueError(
            f'[partner-ecosystem] Could not build JWKS URL from api_url="{api_url}" '
            f'and jwks_path="{jwks_path}".'
        ) from exc

    return ResolvedConfig(
        api_url=base,
        project_id=project_id,
        project_secret=project_secret,
        jwks_uri=jwks_uri,
        issuer=config.issuer,
        audience=config.audience or project_id,
        jwks=config.jwks or JwksOptions(),
    )


def _require_string(value: object, key: str) -> str:
    if not isinstance(value, str) or value.strip() == "":
        raise ValueError(
            f'[partner-ecosystem] Missing required config option "{key}".'
        )
    return value.strip()
