from __future__ import annotations

import base64
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import Path
import json
import os
import re
from typing import Any, Literal, Protocol, cast, runtime_checkable

from govoplan_core.core.module_package_catalog import (
    _canonical_catalog_bytes,
    _catalog_freshness_state,
    _catalog_optional_text,
    _catalog_sequence,
    _catalog_signature_state,
    _catalog_source_exists,
    _catalog_source_type,
    _is_http_url,
    _load_private_key,
    _parse_trusted_keys,
)
from govoplan_core.core.external_references import (
    IntegrationMaturity,
    SOURCE_AUTHORITY_MODES,
    SourceAuthorityMode,
    integration_maturity_rank,
)
from govoplan_core.security.http_fetch import fetch_http_text


CONFIGURATION_PROVIDER_CAPABILITY = "configuration.provider"

DiagnosticSeverity = Literal["blocker", "warning", "info"]
PlanAction = Literal["create", "update", "bind", "skip", "blocked", "noop"]
ConfigurationPackageClass = Literal[
    "reference",
    "product",
    "sector",
    "deployment",
    "integration",
]
ConfigurationPackageEvidenceKind = Literal[
    "target_test",
    "migration",
    "upgrade",
    "recovery",
    "security",
    "operations",
    "accessibility",
    "privacy",
    "documentation",
]

CONFIGURATION_PACKAGE_CLASSES: tuple[ConfigurationPackageClass, ...] = (
    "reference",
    "product",
    "sector",
    "deployment",
    "integration",
)
CONFIGURATION_PACKAGE_EVIDENCE_KINDS: tuple[
    ConfigurationPackageEvidenceKind, ...
] = (
    "target_test",
    "migration",
    "upgrade",
    "recovery",
    "security",
    "operations",
    "accessibility",
    "privacy",
    "documentation",
)
_SHA256_RE = re.compile(r"^sha256:[0-9a-f]{64}$")


@dataclass(frozen=True, slots=True)
class ConfigurationPackageParent:
    package_id: str
    version: str
    relation: Literal["derived_from", "specializes", "extends"] = "derived_from"

    def __post_init__(self) -> None:
        if not self.package_id.strip() or not self.version.strip():
            raise ValueError("Configuration package parent id and version are required.")
        if self.relation not in {"derived_from", "specializes", "extends"}:
            raise ValueError(
                f"Unsupported configuration package parent relation: {self.relation!r}."
            )

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "ConfigurationPackageParent":
        relation = _optional_str(value, "relation") or "derived_from"
        if relation not in {"derived_from", "specializes", "extends"}:
            raise ValueError(f"Unsupported configuration package parent relation: {relation!r}.")
        return cls(
            package_id=_required_str(value, "package_id"),
            version=_required_str(value, "version"),
            relation=relation,
        )

    def to_dict(self) -> dict[str, str]:
        return {
            "package_id": self.package_id,
            "version": self.version,
            "relation": self.relation,
        }


@dataclass(frozen=True, slots=True)
class ConfigurationPackageEvidence:
    kind: ConfigurationPackageEvidenceKind
    reference: str
    summary: str
    checksum: str | None = None

    def __post_init__(self) -> None:
        if self.kind not in CONFIGURATION_PACKAGE_EVIDENCE_KINDS:
            raise ValueError(
                f"Unsupported configuration package evidence kind: {self.kind!r}."
            )
        if not self.reference.strip() or not self.summary.strip():
            raise ValueError(
                "Configuration package evidence reference and summary are required."
            )
        if self.checksum is not None and not _SHA256_RE.fullmatch(self.checksum):
            raise ValueError(
                "Configuration package evidence checksum must use sha256:<64 lowercase hex>."
            )

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "ConfigurationPackageEvidence":
        kind = _required_str(value, "kind")
        if kind not in CONFIGURATION_PACKAGE_EVIDENCE_KINDS:
            raise ValueError(f"Unsupported configuration package evidence kind: {kind!r}.")
        return cls(
            kind=kind,
            reference=_required_str(value, "reference"),
            summary=_required_str(value, "summary"),
            checksum=_optional_str(value, "checksum"),
        )

    def to_dict(self) -> dict[str, object]:
        return {
            "kind": self.kind,
            "reference": self.reference,
            "summary": self.summary,
            "checksum": self.checksum,
        }


@dataclass(frozen=True, slots=True)
class ConfigurationProviderExpectation:
    provider_id: str
    authority_mode: SourceAuthorityMode
    minimum_maturity: IntegrationMaturity
    binding_ref: str | None = None
    health_expectation: str = "healthy"
    freshness_expectation: str | None = None
    recovery_expectation: str | None = None

    def __post_init__(self) -> None:
        if not self.provider_id.strip():
            raise ValueError("Configuration provider expectation id is required.")
        if self.authority_mode not in SOURCE_AUTHORITY_MODES:
            raise ValueError(
                f"Unsupported provider authority mode: {self.authority_mode!r}."
            )
        integration_maturity_rank(self.minimum_maturity)
        if not self.health_expectation.strip():
            raise ValueError("Provider health expectation is required.")

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "ConfigurationProviderExpectation":
        return cls(
            provider_id=_required_str(value, "provider_id"),
            authority_mode=_required_str(value, "authority_mode"),
            minimum_maturity=_required_str(value, "minimum_maturity"),
            binding_ref=_optional_str(value, "binding_ref"),
            health_expectation=_optional_str(value, "health_expectation") or "healthy",
            freshness_expectation=_optional_str(value, "freshness_expectation"),
            recovery_expectation=_optional_str(value, "recovery_expectation"),
        )

    def to_dict(self) -> dict[str, object]:
        return {
            "provider_id": self.provider_id,
            "authority_mode": self.authority_mode,
            "minimum_maturity": self.minimum_maturity,
            "binding_ref": self.binding_ref,
            "health_expectation": self.health_expectation,
            "freshness_expectation": self.freshness_expectation,
            "recovery_expectation": self.recovery_expectation,
        }


@dataclass(frozen=True, slots=True)
class _ConfigurationCatalogValidationState:
    packages: tuple[dict[str, object], ...]
    channel: str | None
    sequence: int | None
    generated_at: str | None
    not_before: str | None
    expires_at: str | None
    signature_state: dict[str, object]
    freshness: dict[str, object]
    replay: dict[str, object]
    read_state: dict[str, object]


@dataclass(frozen=True, slots=True)
class ConfigurationModuleRequirement:
    module_id: str
    version: str | None = None
    optional: bool = False

    def to_dict(self) -> dict[str, object]:
        return {"module_id": self.module_id, "version": self.version, "optional": self.optional}


@dataclass(frozen=True, slots=True)
class ConfigurationPackageFragment:
    module_id: str
    fragment_type: str
    fragment_id: str | None = None
    payload: Mapping[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, object]:
        return {
            "module_id": self.module_id,
            "fragment_type": self.fragment_type,
            "fragment_id": self.fragment_id,
            "payload": dict(self.payload),
        }


@dataclass(frozen=True, slots=True)
class ConfigurationPackageManifest:
    package_id: str
    name: str
    version: str
    package_class: ConfigurationPackageClass = "product"
    description: str | None = None
    publisher: str | None = None
    category: str | None = None
    license: str | None = None
    required_modules: tuple[ConfigurationModuleRequirement, ...] = ()
    required_capabilities: tuple[str, ...] = ()
    optional_modules: tuple[ConfigurationModuleRequirement, ...] = ()
    fragments: tuple[ConfigurationPackageFragment, ...] = ()
    data_requirements: tuple[dict[str, object], ...] = ()
    tags: tuple[str, ...] = ()
    artifact_ref: str | None = None
    artifact_sha256: str | None = None
    signature: Mapping[str, Any] | None = None
    parents: tuple[ConfigurationPackageParent, ...] = ()
    evidence: tuple[ConfigurationPackageEvidence, ...] = ()
    provider_expectations: tuple[ConfigurationProviderExpectation, ...] = ()

    def __post_init__(self) -> None:
        if self.package_class not in CONFIGURATION_PACKAGE_CLASSES:
            raise ValueError(
                f"Unsupported configuration package class: {self.package_class!r}."
            )
        parent_keys = {(item.package_id, item.version) for item in self.parents}
        if len(parent_keys) != len(self.parents):
            raise ValueError("Configuration package parents must be unique.")
        evidence_keys = {(item.kind, item.reference) for item in self.evidence}
        if len(evidence_keys) != len(self.evidence):
            raise ValueError("Configuration package evidence must be unique.")
        provider_ids = [item.provider_id for item in self.provider_expectations]
        if len(provider_ids) != len(set(provider_ids)):
            raise ValueError("Configuration package provider expectations must be unique.")
        for expectation in self.provider_expectations:
            integration_maturity_rank(expectation.minimum_maturity)
        issues = configuration_package_claim_issues(self)
        if issues:
            raise ValueError("Invalid configuration package claim: " + "; ".join(issues))

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "ConfigurationPackageManifest":
        return cls(
            package_id=_required_str(value, "package_id"),
            name=_required_str(value, "name"),
            version=_required_str(value, "version"),
            package_class=_optional_str(value, "package_class") or "product",
            description=_optional_str(value, "description"),
            publisher=_optional_str(value, "publisher"),
            category=_optional_str(value, "category"),
            license=_optional_str(value, "license"),
            required_modules=tuple(_module_requirements(value.get("required_modules"), optional=False)),
            required_capabilities=tuple(_string_list(value.get("required_capabilities"))),
            optional_modules=tuple(_module_requirements(value.get("optional_modules"), optional=True)),
            fragments=tuple(_fragments(value.get("fragments"))),
            data_requirements=tuple(_object_list(value.get("data_requirements"), field_name="data_requirements")),
            tags=tuple(_string_list(value.get("tags"))),
            artifact_ref=_optional_str(value, "artifact_ref"),
            artifact_sha256=_optional_str(value, "artifact_sha256"),
            signature=value.get("signature") if isinstance(value.get("signature"), Mapping) else None,
            parents=tuple(
                ConfigurationPackageParent.from_mapping(item)
                for item in _object_list(value.get("parents"), field_name="parents")
            ),
            evidence=tuple(
                ConfigurationPackageEvidence.from_mapping(item)
                for item in _object_list(value.get("evidence"), field_name="evidence")
            ),
            provider_expectations=tuple(
                ConfigurationProviderExpectation.from_mapping(item)
                for item in _object_list(
                    value.get("provider_expectations"),
                    field_name="provider_expectations",
                )
            ),
        )

    def to_dict(self) -> dict[str, object]:
        payload: dict[str, object] = {
            "package_id": self.package_id,
            "name": self.name,
            "version": self.version,
            "package_class": self.package_class,
            "required_modules": [item.to_dict() for item in self.required_modules],
            "required_capabilities": list(self.required_capabilities),
            "optional_modules": [item.to_dict() for item in self.optional_modules],
            "fragments": [item.to_dict() for item in self.fragments],
            "data_requirements": [dict(item) for item in self.data_requirements],
            "tags": list(self.tags),
            "parents": [item.to_dict() for item in self.parents],
            "evidence": [item.to_dict() for item in self.evidence],
            "provider_expectations": [
                item.to_dict() for item in self.provider_expectations
            ],
        }
        for key, value in (
            ("description", self.description),
            ("publisher", self.publisher),
            ("category", self.category),
            ("license", self.license),
            ("artifact_ref", self.artifact_ref),
            ("artifact_sha256", self.artifact_sha256),
        ):
            if value is not None:
                payload[key] = value
        if self.signature is not None:
            payload["signature"] = dict(self.signature)
        return payload


@dataclass(frozen=True, slots=True)
class ConfigurationDiagnostic:
    severity: DiagnosticSeverity
    code: str
    message: str
    module_id: str | None = None
    object_ref: str | None = None
    resolution: str | None = None

    def to_dict(self) -> dict[str, object]:
        return {
            "severity": self.severity,
            "code": self.code,
            "message": self.message,
            "module_id": self.module_id,
            "object_ref": self.object_ref,
            "resolution": self.resolution,
        }


@dataclass(frozen=True, slots=True)
class ConfigurationPlanItem:
    action: PlanAction
    module_id: str
    fragment_type: str
    fragment_id: str | None = None
    summary: str | None = None

    def to_dict(self) -> dict[str, object]:
        return {
            "action": self.action,
            "module_id": self.module_id,
            "fragment_type": self.fragment_type,
            "fragment_id": self.fragment_id,
            "summary": self.summary,
        }


@dataclass(frozen=True, slots=True)
class ConfigurationRequiredData:
    key: str
    label: str
    data_type: str = "string"
    required: bool = True
    secret: bool = False
    description: str | None = None

    @classmethod
    def from_mapping(cls, value: Mapping[str, Any]) -> "ConfigurationRequiredData":
        return cls(
            key=_required_str(value, "key"),
            label=_optional_str(value, "label") or _required_str(value, "key"),
            data_type=_optional_str(value, "data_type") or _optional_str(value, "type") or "string",
            required=_bool(value.get("required"), default=True),
            secret=_bool(value.get("secret"), default=False),
            description=_optional_str(value, "description"),
        )

    def to_dict(self) -> dict[str, object]:
        return {
            "key": self.key,
            "label": self.label,
            "data_type": self.data_type,
            "required": self.required,
            "secret": self.secret,
            "description": self.description,
        }


@dataclass(frozen=True, slots=True)
class ConfigurationProviderDescription:
    module_id: str
    fragment_types: tuple[str, ...] = ()
    schema_refs: Mapping[str, str] = field(default_factory=dict)
    exported_scopes: tuple[str, ...] = ()


@dataclass(frozen=True, slots=True)
class ConfigurationPreflightContext:
    tenant_id: str | None = None
    operator_user_id: str | None = None
    supplied_data: Mapping[str, Any] = field(default_factory=dict)
    installed_modules: Mapping[str, str] = field(default_factory=dict)
    capabilities: frozenset[str] = frozenset()
    external_provider_declarations: Mapping[str, Mapping[str, Any]] = field(
        default_factory=dict
    )
    external_provider_states: Mapping[str, Mapping[str, Any]] = field(
        default_factory=dict
    )
    dry_run: bool = True


@dataclass(frozen=True, slots=True)
class ConfigurationPreflightResult:
    diagnostics: tuple[ConfigurationDiagnostic, ...] = ()
    required_data: tuple[ConfigurationRequiredData, ...] = ()
    plan: tuple[ConfigurationPlanItem, ...] = ()


@dataclass(frozen=True, slots=True)
class ConfigurationApplyResult:
    diagnostics: tuple[ConfigurationDiagnostic, ...] = ()
    created_refs: Mapping[str, str] = field(default_factory=dict)
    updated_refs: Mapping[str, str] = field(default_factory=dict)


@dataclass(frozen=True, slots=True)
class ConfigurationExportSelection:
    tenant_id: str | None = None
    scopes: tuple[str, ...] = ()
    module_ids: tuple[str, ...] = ()
    object_refs: tuple[str, ...] = ()


@dataclass(frozen=True, slots=True)
class ConfigurationExportResult:
    fragments: tuple[ConfigurationPackageFragment, ...] = ()
    data_requirements: tuple[ConfigurationRequiredData, ...] = ()
    diagnostics: tuple[ConfigurationDiagnostic, ...] = ()


@runtime_checkable
class ConfigurationProvider(Protocol):
    module_id: str

    def describe(self) -> ConfigurationProviderDescription:
        ...

    def preflight(self, fragment: ConfigurationPackageFragment, context: ConfigurationPreflightContext) -> ConfigurationPreflightResult:
        ...

    def apply(self, fragment: ConfigurationPackageFragment, supplied_data: Mapping[str, Any], context: ConfigurationPreflightContext) -> ConfigurationApplyResult:
        ...

    def export(self, selection: ConfigurationExportSelection, context: ConfigurationPreflightContext) -> ConfigurationExportResult:
        ...

    def health(self, import_result: ConfigurationApplyResult, context: ConfigurationPreflightContext) -> tuple[ConfigurationDiagnostic, ...]:
        ...


def dry_run_configuration_package(
    package: ConfigurationPackageManifest | Mapping[str, Any],
    providers: Sequence[ConfigurationProvider] | Mapping[str, ConfigurationProvider],
    context: ConfigurationPreflightContext,
) -> ConfigurationPreflightResult:
    manifest = _configuration_package_manifest(package)
    provider_map = _configuration_provider_map(providers)
    diagnostics: list[ConfigurationDiagnostic] = []
    required_data: list[ConfigurationRequiredData] = []
    plan: list[ConfigurationPlanItem] = []

    diagnostics.extend(_module_requirement_diagnostics(manifest, context))
    diagnostics.extend(_capability_requirement_diagnostics(manifest, context))
    diagnostics.extend(_provider_expectation_diagnostics(manifest, context))
    for item in manifest.data_requirements:
        requirement = ConfigurationRequiredData.from_mapping(item)
        required_data.append(requirement)
        if requirement.required and requirement.key not in context.supplied_data:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="required_data_missing",
                message=f"Required operator data is missing: {requirement.label}.",
                object_ref=requirement.key,
                resolution="Collect this value in the configuration package wizard before applying.",
            ))

    for fragment in manifest.fragments:
        provider = provider_map.get(fragment.module_id)
        if provider is None:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="configuration_provider_missing",
                message=f"No configuration provider is registered for module {fragment.module_id!r}.",
                module_id=fragment.module_id,
                object_ref=fragment.fragment_id or fragment.fragment_type,
                resolution="Install and enable the module version that provides this configuration provider.",
            ))
            plan.append(ConfigurationPlanItem(action="blocked", module_id=fragment.module_id, fragment_type=fragment.fragment_type, fragment_id=fragment.fragment_id, summary="Provider is missing."))
            continue
        description = provider.describe()
        if description.fragment_types and fragment.fragment_type not in description.fragment_types:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="fragment_type_unsupported",
                message=f"Provider {fragment.module_id!r} does not support fragment type {fragment.fragment_type!r}.",
                module_id=fragment.module_id,
                object_ref=fragment.fragment_id or fragment.fragment_type,
                resolution="Use a package version compatible with the installed module provider.",
            ))
            plan.append(ConfigurationPlanItem(action="blocked", module_id=fragment.module_id, fragment_type=fragment.fragment_type, fragment_id=fragment.fragment_id, summary="Fragment type is unsupported."))
            continue
        try:
            result = provider.preflight(fragment, context)
        except Exception as exc:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="provider_preflight_failed",
                message=f"Configuration provider {fragment.module_id!r} preflight failed: {exc}",
                module_id=fragment.module_id,
                object_ref=fragment.fragment_id or fragment.fragment_type,
                resolution="Review provider diagnostics and package fragment payload.",
            ))
            plan.append(ConfigurationPlanItem(action="blocked", module_id=fragment.module_id, fragment_type=fragment.fragment_type, fragment_id=fragment.fragment_id, summary="Provider preflight failed."))
            continue
        diagnostics.extend(result.diagnostics)
        required_data.extend(result.required_data)
        for requirement in result.required_data:
            if requirement.required and requirement.key not in context.supplied_data:
                diagnostics.append(ConfigurationDiagnostic(
                    severity="blocker",
                    code="required_data_missing",
                    message=f"Required operator data is missing: {requirement.label}.",
                    module_id=fragment.module_id,
                    object_ref=requirement.key,
                    resolution="Collect this value in the configuration package wizard before applying.",
                ))
        plan.extend(result.plan or (ConfigurationPlanItem(action="noop", module_id=fragment.module_id, fragment_type=fragment.fragment_type, fragment_id=fragment.fragment_id, summary="Provider reported no changes."),))
    return ConfigurationPreflightResult(
        diagnostics=tuple(_dedupe_diagnostics(diagnostics)),
        required_data=tuple(_dedupe_required_data(required_data)),
        plan=tuple(plan),
    )


def apply_configuration_package(
    package: ConfigurationPackageManifest | Mapping[str, Any],
    providers: Sequence[ConfigurationProvider] | Mapping[str, ConfigurationProvider],
    context: ConfigurationPreflightContext,
    supplied_data: Mapping[str, Any] | None = None,
) -> ConfigurationApplyResult:
    manifest = _configuration_package_manifest(package)
    apply_context = ConfigurationPreflightContext(
        tenant_id=context.tenant_id,
        operator_user_id=context.operator_user_id,
        supplied_data=supplied_data if supplied_data is not None else context.supplied_data,
        installed_modules=context.installed_modules,
        capabilities=context.capabilities,
        external_provider_declarations=context.external_provider_declarations,
        external_provider_states=context.external_provider_states,
        dry_run=False,
    )
    preflight = dry_run_configuration_package(manifest, providers, apply_context)
    blockers = [item for item in preflight.diagnostics if item.severity == "blocker"]
    if blockers:
        return ConfigurationApplyResult(diagnostics=tuple(blockers))
    provider_map = _configuration_provider_map(providers)
    diagnostics: list[ConfigurationDiagnostic] = list(preflight.diagnostics)
    created_refs: dict[str, str] = {}
    updated_refs: dict[str, str] = {}
    for fragment in manifest.fragments:
        provider = provider_map[fragment.module_id]
        try:
            result = provider.apply(fragment, apply_context.supplied_data, apply_context)
            diagnostics.extend(result.diagnostics)
            created_refs.update(result.created_refs)
            updated_refs.update(result.updated_refs)
            diagnostics.extend(provider.health(result, apply_context))
        except Exception as exc:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="provider_apply_failed",
                message=f"Configuration provider {fragment.module_id!r} apply failed: {exc}",
                module_id=fragment.module_id,
                object_ref=fragment.fragment_id or fragment.fragment_type,
                resolution="Stop the import, keep previous configuration, and inspect provider logs.",
            ))
    return ConfigurationApplyResult(
        diagnostics=tuple(_dedupe_diagnostics(diagnostics)),
        created_refs=created_refs,
        updated_refs=updated_refs,
    )


def export_configuration_package(
    providers: Sequence[ConfigurationProvider] | Mapping[str, ConfigurationProvider],
    selection: ConfigurationExportSelection,
    context: ConfigurationPreflightContext,
) -> ConfigurationExportResult:
    provider_map = _configuration_provider_map(providers)
    module_ids = selection.module_ids or tuple(provider_map)
    fragments: list[ConfigurationPackageFragment] = []
    data_requirements: list[ConfigurationRequiredData] = []
    diagnostics: list[ConfigurationDiagnostic] = []
    for module_id in module_ids:
        provider = provider_map.get(module_id)
        if provider is None:
            diagnostics.append(ConfigurationDiagnostic(
                severity="warning",
                code="configuration_provider_missing",
                message=f"No configuration provider is registered for module {module_id!r}; skipping export.",
                module_id=module_id,
                resolution="Enable the module provider before exporting its configuration.",
            ))
            continue
        try:
            result = provider.export(selection, context)
        except Exception as exc:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="provider_export_failed",
                message=f"Configuration provider {module_id!r} export failed: {exc}",
                module_id=module_id,
                resolution="Review provider diagnostics before reusing this package export.",
            ))
            continue
        fragments.extend(result.fragments)
        data_requirements.extend(result.data_requirements)
        diagnostics.extend(result.diagnostics)
    return ConfigurationExportResult(
        fragments=tuple(fragments),
        data_requirements=tuple(_dedupe_required_data(data_requirements)),
        diagnostics=tuple(_dedupe_diagnostics(diagnostics)),
    )


def configuration_package_catalog(
    path: Path | str | None = None,
    *,
    require_trusted: bool | None = None,
    approved_channels: tuple[str, ...] | None = None,
    trusted_keys: dict[str, str] | None = None,
) -> tuple[dict[str, object], ...]:
    validation = validate_configuration_package_catalog(
        path,
        require_trusted=require_trusted,
        approved_channels=approved_channels,
        trusted_keys=trusted_keys,
    )
    if not validation["valid"]:
        raise ValueError(str(validation["error"] or "Configuration package catalog is invalid."))
    return tuple(item for item in validation["packages"] if isinstance(item, dict))


def validate_configuration_package_catalog(
    path: Path | str | None = None,
    *,
    require_trusted: bool | None = None,
    approved_channels: tuple[str, ...] | None = None,
    trusted_keys: dict[str, str] | None = None,
) -> dict[str, object]:
    source = _catalog_source(path)
    configured = source is not None and _catalog_source_exists(source)
    if source is not None and not _catalog_source_exists(source):
        return _validation_result(source, configured=True, packages=(), error=f"Configuration package catalog does not exist: {source}")
    read_state = _configuration_catalog_default_read_state()
    try:
        effective_require_trusted = _configured_require_signature() if require_trusted is None else require_trusted
        effective_approved_channels = _configured_approved_channels() if approved_channels is None else approved_channels
        effective_trusted_keys = trusted_keys if trusted_keys is not None else _configured_trusted_keys()
        state = _configuration_catalog_validation_state(source, trusted_keys=effective_trusted_keys)
        read_state = state.read_state
    except Exception as exc:
        return _validation_result(source, configured=configured, read_state=read_state, packages=(), error=str(exc))
    policy_error = _configuration_catalog_policy_error(
        source,
        configured=configured,
        state=state,
        require_trusted=effective_require_trusted,
        approved_channels=effective_approved_channels,
    )
    if policy_error is not None:
        return policy_error
    return _validation_result(
        source,
        valid=True,
        configured=configured,
        read_state=state.read_state,
        packages=state.packages,
        channel=state.channel,
        sequence=state.sequence,
        generated_at=state.generated_at,
        not_before=state.not_before,
        expires_at=state.expires_at,
        signature_state=state.signature_state,
        warnings=_configuration_catalog_warnings(state),
    )


def _configuration_catalog_validation_state(
    source: Path | str | None,
    *,
    trusted_keys: dict[str, str],
) -> _ConfigurationCatalogValidationState:
    payload, read_state = _read_catalog_payload_with_metadata(source)
    channel = _catalog_channel(payload)
    sequence = _catalog_sequence(payload)
    return _ConfigurationCatalogValidationState(
        packages=_normalize_catalog_packages(payload),
        channel=channel,
        sequence=sequence,
        generated_at=_catalog_optional_text(payload, "generated_at"),
        not_before=_catalog_optional_text(payload, "not_before"),
        expires_at=_catalog_optional_text(payload, "expires_at"),
        signature_state=_catalog_signature_state(payload, trusted_keys=trusted_keys),
        freshness=_catalog_freshness_state(payload),
        replay=_catalog_replay_state(channel=channel, sequence=sequence),
        read_state=read_state,
    )


def _configuration_catalog_policy_error(
    source: Path | str | None,
    *,
    configured: bool,
    state: _ConfigurationCatalogValidationState,
    require_trusted: bool,
    approved_channels: tuple[str, ...],
) -> dict[str, object] | None:
    if state.signature_state.get("fatal"):
        return _configuration_catalog_invalid_result(
            source,
            configured=configured,
            state=state,
            error=str(state.signature_state["error"]),
        )
    if approved_channels and state.channel not in approved_channels:
        return _configuration_catalog_invalid_result(
            source,
            configured=configured,
            state=state,
            error=(
                f"Configuration package catalog channel {state.channel!r} is not approved. "
                f"Approved channels: {', '.join(approved_channels)}."
            ),
        )
    if require_trusted and not state.signature_state["trusted"]:
        return _configuration_catalog_invalid_result(
            source,
            configured=configured,
            state=state,
            error=str(state.signature_state["error"] or "Configuration package catalog must be signed by a trusted key."),
        )
    if not state.freshness["valid"]:
        return _configuration_catalog_invalid_result(
            source,
            configured=configured,
            state=state,
            error=str(state.freshness["error"]),
        )
    if not state.replay["valid"]:
        return _configuration_catalog_invalid_result(
            source,
            configured=configured,
            state=state,
            error=str(state.replay["error"]),
        )
    return None


def _configuration_catalog_invalid_result(
    source: Path | str | None,
    *,
    configured: bool,
    state: _ConfigurationCatalogValidationState,
    error: str,
) -> dict[str, object]:
    return _validation_result(
        source,
        configured=configured,
        read_state=state.read_state,
        packages=(),
        channel=state.channel,
        sequence=state.sequence,
        generated_at=state.generated_at,
        not_before=state.not_before,
        expires_at=state.expires_at,
        signature_state=state.signature_state,
        error=error,
    )


def _configuration_catalog_warnings(state: _ConfigurationCatalogValidationState) -> list[str]:
    warnings = [str(item) for item in state.freshness.get("warnings", ()) if item]
    warnings.extend(str(item) for item in state.replay.get("warnings", ()) if item)
    if not state.signature_state["signed"]:
        warnings.append("Configuration package catalog is unsigned; use only for local development unless signature enforcement is disabled intentionally.")
    elif not state.signature_state["trusted"]:
        warnings.append(str(state.signature_state["error"] or "Catalog signature could not be verified against a trusted key."))
    return warnings


def _configuration_catalog_default_read_state() -> dict[str, object]:
    cache_path = _configured_catalog_cache_path()
    return {"cache_used": False, "cache_path": str(cache_path) if cache_path else None}


def sign_configuration_package_catalog(*, path: Path, key_id: str, private_key_path: Path, output_path: Path | None = None) -> Path:
    payload = _read_catalog_payload(path)
    if not isinstance(payload, dict):
        raise ValueError("Only object-style configuration package catalogs can be signed.")
    signed_payload = dict(payload)
    signed_payload.pop("signature", None)
    signed_payload.pop("signatures", None)
    private_key = _load_private_key(private_key_path)
    signature = private_key.sign(_canonical_catalog_bytes(signed_payload))
    signed_payload["signature"] = {
        "algorithm": "ed25519",
        "key_id": key_id,
        "value": base64.b64encode(signature).decode("ascii"),
    }
    target = output_path or path
    target.write_text(json.dumps(signed_payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
    return target


def record_configuration_package_catalog_acceptance(validation: dict[str, object]) -> None:
    state_path = _configured_sequence_state_path()
    if state_path is None or validation.get("valid") is not True:
        return
    channel = validation.get("channel")
    sequence = validation.get("sequence")
    if not isinstance(channel, str) or not isinstance(sequence, int):
        return
    try:
        state = json.loads(state_path.read_text(encoding="utf-8")) if state_path.exists() else {}
    except json.JSONDecodeError:
        state = {}
    if not isinstance(state, dict):
        state = {}
    channels = state.get("channels")
    if not isinstance(channels, dict):
        channels = {}
    channel_state = channels.get(channel)
    if not isinstance(channel_state, dict):
        channel_state = {}
    channel_state["last_sequence"] = max(int(channel_state.get("last_sequence") or 0), sequence)
    channel_state["accepted_at"] = datetime.now(tz=UTC).isoformat().replace("+00:00", "Z")
    channel_state["key_id"] = validation.get("key_id")
    channel_state["source"] = validation.get("source") or validation.get("path")
    channels[channel] = channel_state
    state["channels"] = channels
    state_path.parent.mkdir(parents=True, exist_ok=True)
    state_path.write_text(json.dumps(state, indent=2, sort_keys=True) + "\n", encoding="utf-8")


def configuration_package_claim_issues(
    manifest: ConfigurationPackageManifest,
) -> tuple[str, ...]:
    evidence_kinds = {item.kind for item in manifest.evidence}
    required_evidence: dict[str, frozenset[str]] = {
        "reference": frozenset(
            {
                "target_test",
                "recovery",
                "security",
                "operations",
                "accessibility",
                "privacy",
                "documentation",
            }
        ),
        "product": frozenset(),
        "sector": frozenset({"documentation"}),
        "deployment": frozenset(
            {"target_test", "recovery", "security", "operations"}
        ),
        "integration": frozenset(
            {"target_test", "recovery", "operations", "documentation"}
        ),
    }
    issues: list[str] = []
    missing = sorted(required_evidence[manifest.package_class] - evidence_kinds)
    if missing:
        issues.append(
            f"{manifest.package_class} package is missing evidence: "
            + ", ".join(missing)
        )
    if manifest.package_class in {"reference", "deployment", "integration"}:
        unbound = sorted(
            item.kind
            for item in manifest.evidence
            if item.kind != "documentation" and item.checksum is None
        )
        if unbound:
            issues.append(
                f"{manifest.package_class} package has evidence without checksums: "
                + ", ".join(unbound)
            )
    if manifest.package_class == "sector" and not manifest.parents:
        issues.append("sector packages must declare a parent package/version")
    if manifest.package_class == "integration" and not manifest.provider_expectations:
        issues.append("integration packages must declare external provider expectations")
    return tuple(issues)


def validate_configuration_package_derivation(
    child: ConfigurationPackageManifest,
    parent: ConfigurationPackageManifest,
) -> tuple[ConfigurationDiagnostic, ...]:
    diagnostics: list[ConfigurationDiagnostic] = []
    if not any(
        item.package_id == parent.package_id and item.version == parent.version
        for item in child.parents
    ):
        diagnostics.append(
            ConfigurationDiagnostic(
                severity="blocker",
                code="package_parent_provenance_missing",
                message=(
                    f"Package {child.package_id!r} does not declare parent "
                    f"{parent.package_id}@{parent.version}."
                ),
                object_ref=parent.package_id,
            )
        )
    child_modules = {item.module_id: item for item in child.required_modules}
    for requirement in parent.required_modules:
        candidate = child_modules.get(requirement.module_id)
        if candidate is None or (
            requirement.version is not None
            and candidate.version != requirement.version
        ):
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="package_parent_module_constraint_loosened",
                    message=(
                        f"Derived package loosens parent module requirement "
                        f"{requirement.module_id!r}."
                    ),
                    module_id=requirement.module_id,
                )
            )
    for capability in set(parent.required_capabilities) - set(
        child.required_capabilities
    ):
        diagnostics.append(
            ConfigurationDiagnostic(
                severity="blocker",
                code="package_parent_capability_constraint_loosened",
                message=(
                    f"Derived package removes required capability {capability!r}."
                ),
                object_ref=capability,
            )
        )
    child_providers = {
        item.provider_id: item for item in child.provider_expectations
    }
    for expectation in parent.provider_expectations:
        candidate = child_providers.get(expectation.provider_id)
        if candidate is None:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="package_parent_provider_constraint_removed",
                    message=(
                        f"Derived package removes provider expectation "
                        f"{expectation.provider_id!r}."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
            continue
        if candidate.authority_mode != expectation.authority_mode:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="package_parent_authority_mode_changed",
                    message=(
                        f"Derived package changes authority mode for provider "
                        f"{expectation.provider_id!r}."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
        if integration_maturity_rank(
            candidate.minimum_maturity
        ) < integration_maturity_rank(expectation.minimum_maturity):
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="package_parent_provider_maturity_loosened",
                    message=(
                        f"Derived package lowers provider maturity for "
                        f"{expectation.provider_id!r}."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
    return tuple(diagnostics)


def _configuration_package_manifest(package: ConfigurationPackageManifest | Mapping[str, Any]) -> ConfigurationPackageManifest:
    if isinstance(package, ConfigurationPackageManifest):
        return package
    return ConfigurationPackageManifest.from_mapping(package)


def _configuration_provider_map(providers: Sequence[ConfigurationProvider] | Mapping[str, ConfigurationProvider]) -> dict[str, ConfigurationProvider]:
    if isinstance(providers, Mapping):
        return {str(key): provider for key, provider in providers.items()}
    return {provider.module_id: provider for provider in providers}


def _module_requirement_diagnostics(manifest: ConfigurationPackageManifest, context: ConfigurationPreflightContext) -> list[ConfigurationDiagnostic]:
    diagnostics: list[ConfigurationDiagnostic] = []
    installed = context.installed_modules
    for requirement in manifest.required_modules:
        installed_version = installed.get(requirement.module_id)
        if installed_version is None:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="required_module_missing",
                message=f"Required module {requirement.module_id!r} is not installed.",
                module_id=requirement.module_id,
                resolution="Install and enable the required module before applying this configuration package.",
            ))
        elif requirement.version and installed_version != requirement.version:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="required_module_version_mismatch",
                message=f"Required module {requirement.module_id!r} needs version {requirement.version}, but {installed_version} is installed.",
                module_id=requirement.module_id,
                resolution="Install a compatible module version or use a matching configuration package.",
            ))
    return diagnostics


def _capability_requirement_diagnostics(manifest: ConfigurationPackageManifest, context: ConfigurationPreflightContext) -> list[ConfigurationDiagnostic]:
    diagnostics: list[ConfigurationDiagnostic] = []
    capabilities = set(context.capabilities)
    for capability in manifest.required_capabilities:
        if capability not in capabilities:
            diagnostics.append(ConfigurationDiagnostic(
                severity="blocker",
                code="required_capability_missing",
                message=f"Required capability {capability!r} is not available.",
                object_ref=capability,
                resolution="Enable the module or platform capability before applying this configuration package.",
            ))
    return diagnostics


def _provider_expectation_diagnostics(
    manifest: ConfigurationPackageManifest,
    context: ConfigurationPreflightContext,
) -> list[ConfigurationDiagnostic]:
    diagnostics: list[ConfigurationDiagnostic] = []
    for expectation in manifest.provider_expectations:
        declaration = context.external_provider_declarations.get(
            expectation.provider_id
        )
        if declaration is None:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="external_provider_missing",
                    message=(
                        f"Required external provider {expectation.provider_id!r} "
                        "is not installed or declared."
                    ),
                    object_ref=expectation.provider_id,
                    resolution=(
                        "Install and enable a module exposing the declared provider."
                    ),
                )
            )
            continue
        supported_modes = {
            str(item)
            for item in declaration.get("authority_modes", ())
            if str(item).strip()
        }
        if expectation.authority_mode not in supported_modes:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="external_provider_authority_mode_unsupported",
                    message=(
                        f"Provider {expectation.provider_id!r} does not support "
                        f"authority mode {expectation.authority_mode!r}."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
        actual_maturity = str(declaration.get("maturity") or "discover")
        try:
            maturity_sufficient = integration_maturity_rank(
                cast(IntegrationMaturity, actual_maturity)
            ) >= integration_maturity_rank(expectation.minimum_maturity)
        except ValueError:
            maturity_sufficient = False
        if not maturity_sufficient:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="external_provider_maturity_insufficient",
                    message=(
                        f"Provider {expectation.provider_id!r} has maturity "
                        f"{actual_maturity!r}; {expectation.minimum_maturity!r} is required."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
        provider_state = context.external_provider_states.get(
            expectation.provider_id
        )
        if provider_state is None:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="warning",
                    code="external_provider_health_unverified",
                    message=(
                        f"Provider {expectation.provider_id!r} has no current "
                        "health/freshness observation."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
            continue
        state = provider_state
        if expectation.binding_ref is not None:
            bindings = provider_state.get("bindings")
            matching_binding = next(
                (
                    item
                    for item in bindings
                    if isinstance(item, Mapping)
                    and str(item.get("binding_ref") or "")
                    == expectation.binding_ref
                ),
                None,
            ) if isinstance(bindings, Sequence) and not isinstance(
                bindings, (str, bytes)
            ) else None
            if matching_binding is None and str(
                provider_state.get("binding_ref") or ""
            ) == expectation.binding_ref:
                matching_binding = provider_state
            if matching_binding is None:
                diagnostics.append(
                    ConfigurationDiagnostic(
                        severity="blocker",
                        code="external_provider_binding_mismatch",
                        message=(
                            f"Provider {expectation.provider_id!r} is not observed through "
                            f"required binding {expectation.binding_ref!r}."
                        ),
                        object_ref=expectation.provider_id,
                    )
                )
                continue
            state = matching_binding
        health = str(state.get("health") or state.get("health_state") or "unknown")
        accepted_health = (
            {"ok", "healthy"}
            if expectation.health_expectation == "healthy"
            else {expectation.health_expectation}
        )
        if health not in accepted_health:
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="external_provider_unhealthy",
                    message=(
                        f"Provider {expectation.provider_id!r} health is {health!r}."
                    ),
                    object_ref=expectation.provider_id,
                    resolution="Restore provider health or use a documented degraded path.",
                )
            )
        observed_authority_mode = str(state.get("authority_mode") or "")
        if (
            observed_authority_mode
            and observed_authority_mode != expectation.authority_mode
        ):
            diagnostics.append(
                ConfigurationDiagnostic(
                    severity="blocker",
                    code="external_provider_binding_authority_mismatch",
                    message=(
                        f"Provider {expectation.provider_id!r} is configured as "
                        f"{observed_authority_mode!r}; {expectation.authority_mode!r} "
                        "is required."
                    ),
                    object_ref=expectation.provider_id,
                )
            )
        if expectation.freshness_expectation is not None:
            freshness = str(
                state.get("freshness")
                or state.get("freshness_state")
                or "unknown"
            )
            if freshness != expectation.freshness_expectation:
                diagnostics.append(
                    ConfigurationDiagnostic(
                        severity="blocker",
                        code="external_provider_freshness_expectation_failed",
                        message=(
                            f"Provider {expectation.provider_id!r} freshness is "
                            f"{freshness!r}; {expectation.freshness_expectation!r} is required."
                        ),
                        object_ref=expectation.provider_id,
                    )
                )
        if expectation.recovery_expectation is not None:
            behavior = declaration.get("behavior")
            declared_recovery = (
                behavior.get(expectation.recovery_expectation)
                if isinstance(behavior, Mapping)
                else None
            )
            observed_recovery = state.get("recovery") or state.get(
                "recovery_state"
            )
            if not declared_recovery and observed_recovery != expectation.recovery_expectation:
                diagnostics.append(
                    ConfigurationDiagnostic(
                        severity="blocker",
                        code="external_provider_recovery_expectation_failed",
                        message=(
                            f"Provider {expectation.provider_id!r} does not satisfy "
                            f"recovery expectation {expectation.recovery_expectation!r}."
                        ),
                        object_ref=expectation.provider_id,
                    )
                )
    return diagnostics


def _dedupe_diagnostics(items: Sequence[ConfigurationDiagnostic]) -> list[ConfigurationDiagnostic]:
    seen: set[tuple[object, ...]] = set()
    result: list[ConfigurationDiagnostic] = []
    for item in items:
        key = (item.severity, item.code, item.module_id, item.object_ref, item.message)
        if key in seen:
            continue
        seen.add(key)
        result.append(item)
    return result


def _dedupe_required_data(items: Sequence[ConfigurationRequiredData]) -> list[ConfigurationRequiredData]:
    seen: set[str] = set()
    result: list[ConfigurationRequiredData] = []
    for item in items:
        if item.key in seen:
            continue
        seen.add(item.key)
        result.append(item)
    return result


def _catalog_source(path: Path | str | None) -> Path | str | None:
    if path is not None:
        return path if isinstance(path, str) and _is_http_url(path) else Path(path).expanduser()
    url = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_URL", "").strip()
    if url:
        return url
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG", "").strip()
    return Path(value).expanduser() if value else None


def _configured_catalog_cache_path() -> Path | None:
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_CACHE", "").strip()
    return Path(value).expanduser() if value else None


def _configured_sequence_state_path() -> Path | None:
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_SEQUENCE_STATE", "").strip()
    return Path(value).expanduser() if value else None


def _configured_enforce_sequence() -> bool:
    return os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_ENFORCE_SEQUENCE", "").strip().lower() in {"1", "true", "yes", "on"}


def _configured_require_signature() -> bool:
    return os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_REQUIRE_SIGNATURE", "").strip().lower() in {"1", "true", "yes", "on"}


def _configured_approved_channels() -> tuple[str, ...]:
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_APPROVED_CHANNELS", "").strip()
    return tuple(item.strip() for item in value.split(",") if item.strip()) if value else ()


def _configured_trusted_keys() -> dict[str, str]:
    file_value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_TRUSTED_KEYS_FILE", "").strip()
    if file_value:
        path = Path(file_value).expanduser()
        if not path.exists():
            raise ValueError(f"Trusted configuration catalog key file does not exist: {path}")
        return _parse_trusted_keys(path.read_text(encoding="utf-8"))
    url_value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_TRUSTED_KEYS_URL", "").strip()
    if url_value:
        return _parse_trusted_keys(_read_trusted_keys_url(url_value))
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_TRUSTED_KEYS", "").strip()
    return _parse_trusted_keys(value) if value else {}


def _configured_trusted_keys_cache_path() -> Path | None:
    value = os.getenv("GOVOPLAN_CONFIGURATION_PACKAGE_CATALOG_TRUSTED_KEYS_CACHE", "").strip()
    return Path(value).expanduser() if value else None


def _read_trusted_keys_url(url: str) -> str:
    cache_path = _configured_trusted_keys_cache_path()
    try:
        body = fetch_http_text(url, timeout=15, label="Trusted configuration catalog key URL")
        if cache_path is not None:
            cache_path.parent.mkdir(parents=True, exist_ok=True)
            cache_path.write_text(body, encoding="utf-8")
        return body
    except OSError:
        if cache_path is not None and cache_path.exists():
            return cache_path.read_text(encoding="utf-8")
        raise


def _read_catalog_payload(source: Path | str | None) -> object:
    payload, _metadata = _read_catalog_payload_with_metadata(source)
    return payload


def _read_catalog_payload_with_metadata(source: Path | str | None) -> tuple[object, dict[str, object]]:
    cache_path = _configured_catalog_cache_path()
    metadata: dict[str, object] = {"cache_used": False, "cache_path": str(cache_path) if cache_path else None}
    if source is None:
        return {"packages": []}, metadata
    if isinstance(source, str) and _is_http_url(source):
        try:
            body = fetch_http_text(source, timeout=15, label="Configuration package catalog URL")
            if cache_path is not None:
                cache_path.parent.mkdir(parents=True, exist_ok=True)
                cache_path.write_text(body, encoding="utf-8")
            return json.loads(body), metadata
        except OSError:
            if cache_path is not None and cache_path.exists():
                metadata["cache_used"] = True
                return json.loads(cache_path.read_text(encoding="utf-8")), metadata
            raise
    return json.loads(Path(source).read_text(encoding="utf-8")), metadata


def _normalize_catalog_packages(payload: object) -> tuple[dict[str, object], ...]:
    raw_items = payload.get("packages") if isinstance(payload, dict) else payload
    if not isinstance(raw_items, list):
        raise ValueError("Configuration package catalog must be a list or an object with a 'packages' list.")
    return tuple(ConfigurationPackageManifest.from_mapping(item).to_dict() for item in raw_items if isinstance(item, Mapping))


def _catalog_channel(payload: object) -> str | None:
    if not isinstance(payload, dict):
        return None
    value = payload.get("channel")
    return str(value).strip() if value is not None and str(value).strip() else None


def _catalog_replay_state(*, channel: str | None, sequence: int | None) -> dict[str, object]:
    state_path = _configured_sequence_state_path()
    if state_path is None:
        return {"valid": True, "warnings": ()}
    if not channel:
        return {"valid": False, "error": "Configuration package catalog sequence replay protection needs a channel."}
    if sequence is None:
        return {"valid": False, "error": "Configuration package catalog sequence replay protection needs a sequence."}
    if not state_path.exists():
        return {"valid": True, "warnings": ()}
    try:
        state = json.loads(state_path.read_text(encoding="utf-8"))
    except json.JSONDecodeError:
        return {"valid": False, "error": f"Configuration catalog sequence state file is not valid JSON: {state_path}"}
    channels = state.get("channels") if isinstance(state, dict) else None
    channel_state = channels.get(channel) if isinstance(channels, dict) else None
    last_sequence = channel_state.get("last_sequence") if isinstance(channel_state, dict) else None
    if last_sequence is None:
        return {"valid": True, "warnings": ()}
    last = int(last_sequence)
    if sequence < last:
        return {"valid": False, "error": f"Configuration package catalog sequence {sequence} is older than accepted sequence {last} for channel {channel!r}."}
    if sequence == last and _configured_enforce_sequence():
        return {"valid": False, "error": f"Configuration package catalog sequence {sequence} was already accepted for channel {channel!r}."}
    return {"valid": True, "warnings": ()}


def _validation_result(
    source: Path | str | None,
    *,
    valid: bool = False,
    configured: bool = False,
    read_state: Mapping[str, object] | None = None,
    packages: Sequence[Mapping[str, object]] = (),
    channel: str | None = None,
    sequence: int | None = None,
    generated_at: str | None = None,
    not_before: str | None = None,
    expires_at: str | None = None,
    signature_state: Mapping[str, object] | None = None,
    warnings: Sequence[str] = (),
    error: str | None = None,
) -> dict[str, object]:
    state = signature_state or {"signed": False, "trusted": False, "key_id": None}
    read_state = read_state or {}
    return {
        "valid": valid,
        "configured": configured,
        "path": str(source) if source is not None else None,
        "source": str(source) if source is not None else None,
        "source_type": _catalog_source_type(source),
        "cache_used": bool(read_state.get("cache_used")),
        "cache_path": read_state.get("cache_path") if isinstance(read_state.get("cache_path"), str) else None,
        "packages": [dict(item) for item in packages],
        "channel": channel,
        "sequence": sequence,
        "generated_at": generated_at,
        "not_before": not_before,
        "expires_at": expires_at,
        "signed": bool(state.get("signed")),
        "trusted": bool(state.get("trusted")),
        "key_id": state.get("key_id"),
        "warnings": list(warnings),
        "error": error,
    }


def _module_requirements(value: object, *, optional: bool) -> list[ConfigurationModuleRequirement]:
    if value is None:
        return []
    if not isinstance(value, list):
        raise ValueError("Configuration package module requirements must be lists.")
    result: list[ConfigurationModuleRequirement] = []
    for item in value:
        if isinstance(item, str):
            result.append(ConfigurationModuleRequirement(module_id=item, optional=optional))
        elif isinstance(item, Mapping):
            result.append(ConfigurationModuleRequirement(module_id=_required_str(item, "module_id"), version=_optional_str(item, "version"), optional=optional))
        else:
            raise ValueError("Configuration package module requirements must be strings or objects.")
    return result


def _fragments(value: object) -> list[ConfigurationPackageFragment]:
    if value is None:
        return []
    if not isinstance(value, list):
        raise ValueError("Configuration package fragments must be a list.")
    result: list[ConfigurationPackageFragment] = []
    for item in value:
        if not isinstance(item, Mapping):
            raise ValueError("Configuration package fragments must be objects.")
        payload = item.get("payload")
        result.append(ConfigurationPackageFragment(
            module_id=_required_str(item, "module_id"),
            fragment_type=_required_str(item, "fragment_type"),
            fragment_id=_optional_str(item, "fragment_id"),
            payload=payload if isinstance(payload, Mapping) else {},
        ))
    return result


def _object_list(value: object, *, field_name: str) -> list[dict[str, object]]:
    if value is None:
        return []
    if not isinstance(value, list):
        raise ValueError(f"Configuration package {field_name} must be a list.")
    return [dict(item) for item in value if isinstance(item, Mapping)]


def _string_list(value: object) -> list[str]:
    if value is None:
        return []
    if not isinstance(value, list):
        raise ValueError("Configuration package list fields must be lists.")
    return [str(item).strip() for item in value if str(item).strip()]


def _bool(value: object, *, default: bool) -> bool:
    if value is None:
        return default
    if isinstance(value, bool):
        return value
    return str(value).strip().casefold() in {"1", "true", "yes", "on"}


def _required_str(value: Mapping[str, Any], key: str) -> str:
    item = _optional_str(value, key)
    if not item:
        raise ValueError(f"Configuration package entry is missing {key!r}.")
    return item


def _optional_str(value: Mapping[str, Any], key: str) -> str | None:
    item = value.get(key)
    if item is None:
        return None
    text = str(item).strip()
    return text or None
