"""Repair and migration accessors for a verified WeeklyOperations authority."""
from __future__ import annotations

import os
from dataclasses import dataclass
from pathlib import Path

from checkin_cli.weekly_operations import (
    CustomerIdentityDigest, WeeklyOperationsCorruption,
    WeeklyOperationsInputError, customer_storage_digest,
)
from checkin_cli.weekly_operations_parent import (
    WeeklyOperationsAuthorityBinding, WeeklyOperationsParentAuthority,
    validate_authority_binding,
)
from checkin_cli.weekly_operations_repair import inspect_repair_target
from checkin_cli.weekly_operations_authority_root import (
    WeeklyOperationsAuthorityRoot, verify_authority_descriptor,
)


@dataclass(frozen=True, slots=True)
class LegacySidecarInventory:
    checked_roots: int
    discovered: tuple[Path, ...]


class WeeklyOperationsMigrationRequired(WeeklyOperationsCorruption):
    """Legacy customer-tree sidecars require an explicit future migration."""


def _inspect_repair(
    descriptor: int, binding: WeeklyOperationsAuthorityBinding,
    customer_identity: CustomerIdentityDigest,
):
    repair_digest = customer_storage_digest(customer_identity)
    verify_authority_descriptor(descriptor, binding, repair_target_digest=repair_digest)
    return inspect_repair_target(descriptor, customer_identity)


def issue_repair_authority(authority: WeeklyOperationsAuthorityRoot, customer_identity: CustomerIdentityDigest) -> WeeklyOperationsAuthorityRoot:
    """Issue a repair-only duplicate of an active pinned authority."""
    if authority.repair_binding is not None:
        raise WeeklyOperationsInputError("repair authority cannot issue another repair authority")
    with authority.parent.locked():
        authority.verify_name_locked()
        descriptor = os.dup(authority.descriptor)
        try:
            repair_binding = _inspect_repair(descriptor, authority.binding, customer_identity)
            return WeeklyOperationsAuthorityRoot(authority.parent, descriptor, authority.binding, repair_binding)
        except WeeklyOperationsCorruption:
            os.close(descriptor)
            raise


def open_authority_root_for_repair(
    parent: WeeklyOperationsParentAuthority, binding: WeeklyOperationsAuthorityBinding,
    customer_identity: CustomerIdentityDigest,
) -> WeeklyOperationsAuthorityRoot:
    """Open one strictly proven repair capability through the pinned root."""
    validate_authority_binding(binding)
    with parent.locked():
        descriptor = os.dup(parent.descriptor)
        try:
            repair_binding = _inspect_repair(descriptor, binding, customer_identity)
            return WeeklyOperationsAuthorityRoot(parent, descriptor, binding, repair_binding)
        except WeeklyOperationsCorruption:
            os.close(descriptor)
            raise


def discover_legacy_sidecars(customer_roots: tuple[Path, ...]) -> LegacySidecarInventory:
    discovered = tuple(
        root / "nutrition-plans" / "weekly-operations.jsonl"
        for root in customer_roots
        if (root / "nutrition-plans" / "weekly-operations.jsonl").exists()
    )
    inventory = LegacySidecarInventory(len(customer_roots), discovered)
    if discovered:
        raise WeeklyOperationsMigrationRequired("migration_required")
    return inventory
