"""Bounded migration authority for one pre-existing activation-v1 customer."""

from __future__ import annotations

import re
from pathlib import Path

from checkin_cli.nutrition_onboarding_contract import canonical_digest
from checkin_cli.nutrition_onboarding_fs import (
    atomic_write_private_json,
    read_private_json,
    validate_profile_path,
)
from checkin_cli.nutrition_onboarding_projection import (
    build_legacy_activation_authority,
    customer_nutrition_projection_digest,
)


def legacy_migration_preflight(
    *,
    profile_root: Path,
    expected_enabled_customer: str,
    owner_digest: str,
) -> dict[str, str]:
    if not re.fullmatch(r"[0-9a-f]{64}", owner_digest):
        raise ValueError("owner_digest must be a lowercase SHA-256 digest")
    root = Path(profile_root)
    registry_path = root / "customers" / "registry.json"
    journal_path = root / "data" / "customer-activation-journal.json"
    validate_profile_path(registry_path, root)
    validate_profile_path(journal_path, root)
    registry = read_private_json(registry_path)
    if not isinstance(registry, dict) or not isinstance(registry.get("customers"), list):
        raise ValueError("registry customers are invalid")
    enabled = [
        customer
        for customer in registry["customers"]
        if isinstance(customer, dict) and customer.get("enabled") is True
    ]
    if len(enabled) != 1 or enabled[0].get("customer_key") != expected_enabled_customer:
        raise ValueError("enabled legacy customer does not match confirmation")
    journal = read_private_json(journal_path)
    if (
        not isinstance(journal, dict)
        or journal.get("version") != 1
        or journal.get("state") != "committed"
        or journal.get("customer_id") != expected_enabled_customer
    ):
        raise ValueError("legacy activation receipt is not an exact committed v1 receipt")
    return {
        "customer_key": expected_enabled_customer,
        "activation_receipt_digest": canonical_digest(journal),
        "registry_projection_digest": customer_nutrition_projection_digest(enabled[0]),
        "owner_digest": owner_digest,
    }


def commit_legacy_migration(
    *,
    profile_root: Path,
    expected_enabled_customer: str,
    owner_digest: str,
    confirm_activation_receipt_digest: str,
) -> dict[str, str]:
    preflight = legacy_migration_preflight(
        profile_root=profile_root,
        expected_enabled_customer=expected_enabled_customer,
        owner_digest=owner_digest,
    )
    if preflight["activation_receipt_digest"] != confirm_activation_receipt_digest:
        raise ValueError("activation receipt confirmation does not match preflight")
    manifest = build_legacy_activation_authority(
        customer_key=preflight["customer_key"],
        activation_receipt_digest=preflight["activation_receipt_digest"],
        registry_projection_digest=preflight["registry_projection_digest"],
        owner_digest=preflight["owner_digest"],
    )
    path = (
        Path(profile_root)
        / "data"
        / "migrations"
        / "nutrition-readiness-v1"
        / "legacy-activation-authority.json"
    )
    validate_profile_path(path, Path(profile_root))
    path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
    path.parent.chmod(0o700)
    atomic_write_private_json(path, manifest)
    return {
        "manifest_path": str(path),
        "manifest_digest": manifest["digest"],
        **preflight,
    }
