"""Runtime helpers for CLI/orchestrator integration."""

from __future__ import annotations

from typing import Sequence
import os
import sys

from .client import (
    DEFAULT_LAYERS,
    DEFAULT_LICENSE_ID,
    LicenseContext,
    LicenseValidationError,
    LicenseValidator,
)


def resolve_license_context(
    *,
    license_id: str | None = None,
    license_repo: str | None = None,
    default_repo: str | None = None,
    required_layers: Sequence[str] | None = None,
) -> LicenseContext:
    """Resolve user input + env vars into a LicenseContext."""

    effective_id = (
        license_id or os.getenv("TOKENMOULDS_LICENSE_ID") or DEFAULT_LICENSE_ID
    )
    repo = license_repo or os.getenv("TOKENMOULDS_LICENSE_REPO") or default_repo
    layers = tuple(required_layers) if required_layers else DEFAULT_LAYERS
    return LicenseContext(
        license_id=effective_id, repository=repo, required_layers=layers
    )


def validate_or_exit(
    context: LicenseContext,
    *,
    registry_path: str | None = None,
    validator: LicenseValidator | None = None,
    quiet: bool = False,
):
    """Validate the license context, exiting the process if invalid.

    Returns the LicenseValidationResult when successful.
    """

    active_validator = validator or LicenseValidator(registry_path=registry_path)
    try:
        result = active_validator.validate(context)
    except LicenseValidationError as exc:
        print(f"❌ License validation failed: {exc}", file=sys.stderr)
        sys.exit(2)

    message = _describe_license(
        result.license_id, result.plan, result.expires_at, result.mode
    )
    if not quiet:
        print(message)
    return result


def _describe_license(license_id: str, plan: str, expires_at, mode: str) -> str:
    suffix = f"(mode: {mode})" if mode != "strict" else ""
    expiry = f", expires {expires_at.isoformat()}" if expires_at else ""
    return f"🔐 License {license_id} ({plan}) validated{expiry} {suffix}".strip()
