"""CROWD model-contract seam, not a model probe or a trust/certification service.

The empty template deliberately cannot validate. Canonical class IDs are local
0=person/1=head; raw slots, background count and query count are never inferred
from the old pbtxt or from the words 'two classes'.
"""
from dataclasses import asdict, dataclass
import re

from app.crowd_config import CROWD_MODEL, FRAME_OBJECT_LIMIT


@dataclass(frozen=True)
class CrowdTensorContract:
    query_count: int
    logit_count: int
    person_slot: int
    head_slot: int
    ignored_slots: tuple[int, ...]
    checkpoint_sha256: str
    onnx_sha256: str
    review_id: str
    # This seam implements only these explicitly declared semantics.
    box_format: str
    score_format: str
    output_dtype: str
    selection_policy: str

    def __post_init__(self):
        if type(self.query_count) is not int or not 1 <= self.query_count <= 4096:
            raise ValueError('CROWD_QUERY_CONTRACT_INVALID')
        if type(self.logit_count) is not int or not 2 <= self.logit_count <= 256:
            raise ValueError('CROWD_LOGIT_CONTRACT_INVALID')
        slots = (self.person_slot, self.head_slot, *self.ignored_slots)
        if any(type(s) is not int for s in slots) or sorted(slots) != list(range(self.logit_count)):
            raise ValueError('CROWD_CLASS_MAPPING_INCOMPLETE')
        for value in (self.checkpoint_sha256, self.onnx_sha256):
            if type(value) is not str or re.fullmatch(r'[0-9a-f]{64}', value) is None:
                raise ValueError('CROWD_PROVENANCE_REQUIRED')
        if type(self.review_id) is not str or not self.review_id.strip() or len(self.review_id) > 128:
            raise ValueError('CROWD_MODEL_REVIEW_REQUIRED')
        if (self.box_format != 'CXCYWH_NORMALIZED' or self.score_format != 'RAW_SIGMOID_LOGITS'
                or self.output_dtype != 'FP32'
                or self.selection_policy != 'GLOBAL_TOP300_THEN_MAP'):
            raise ValueError('CROWD_OUTPUT_SEMANTICS_UNSUPPORTED')
        object.__setattr__(self, 'ignored_slots', tuple(self.ignored_slots))

    def validate_shapes(self, dets_shape, labels_shape, *, batch):
        if (type(batch) is not int or not 1 <= batch <= 8
                or tuple(dets_shape) != (batch, self.query_count, 4)
                or tuple(labels_shape) != (batch, self.query_count, self.logit_count)):
            raise ValueError('CROWD_OUTPUT_SHAPE_MISMATCH')

    def canonical_class(self, raw_slot):
        if type(raw_slot) is not int or not 0 <= raw_slot < self.logit_count:
            raise ValueError('CROWD_RAW_SLOT_INVALID')
        return 0 if raw_slot == self.person_slot else 1 if raw_slot == self.head_slot else None


@dataclass(frozen=True)
class CrowdBuildIntent:
    """Unexecuted candidate settings. This never emits/loads an engine or pbtxt."""
    instances: int = 8
    min_batch: int = 1
    opt_batch: int = 4
    max_batch: int = 4
    resolution: int = 512

    def __post_init__(self):
        if type(self.instances) is not int or not 1 <= self.instances <= 16:
            raise ValueError('Invalid CROWD instance count.')
        values = (self.min_batch, self.opt_batch, self.max_batch)
        if any(type(v) is not int for v in values) or not 1 <= self.min_batch <= self.opt_batch <= self.max_batch <= 8:
            raise ValueError('Invalid CROWD batch profile.')
        if type(self.resolution) is not int or self.resolution != 512:
            raise ValueError('CROWD input changes require a new reviewed contract.')

    def payload(self):
        return dict(asdict(self), model=CROWD_MODEL, precision='FP16_CANDIDATE',
                    status='BUILD_INTENT_NOT_VERIFIED', model_contract='UNCONFIRMED',
                    max_public_objects=FRAME_OBJECT_LIMIT)


def unconfirmed_manifest():
    """A blank provenance/checklist template, not a fabricated manifest PASS."""
    return dict(origin='Awiros/person_and_head_detection',
                checkpoint_path='ckpts/rf-detrs/checkpoint_best_total.safetensors',
                source_revision=None, checkpoint_sha256=None, exporter_revision=None,
                onnx_sha256=None, engine_sha256=None, raw_contract=None,
                preprocessing=None, build_intent=CrowdBuildIntent().payload(),
                status='NEEDS_MODEL_CONTRACT_CONFIRMATION',
                checkpoint_load='NOT_RUN', onnx_probe='NOT_RUN', triton_smoke='NOT_RUN',
                numerical_parity='NOT_RUN', runtime='NOT_RUN')
