"""Visible deterministic rules for the MKN-030 synthetic portability lab."""
from __future__ import annotations

def resource_map(f): return {r.get('resource_id'):r for r in (f.get('resources') or []) if r.get('resource_id')}

def inspect(f):
    issues=[]
    if not isinstance(f,dict): return ['INPUT_INVALID']
    pkg=f.get('package') or {}; resources=f.get('resources') or []; manifest=f.get('manifest') or {}; target=f.get('target') or {}; imports=f.get('import_result') or []; rt=(f.get('round_trip') or {}).get('resources') or []; review=f.get('review') or {}
    rm=resource_map(f); declared=set(manifest.get('declared_resource_ids') or [])
    if not pkg.get('package_id') or not pkg.get('manifest_version') or not pkg.get('canonical_content_ref') or not pkg.get('source_snapshot_ref') or not pkg.get('exporter_version'): issues.append('PACKAGE_EVIDENCE_MISSING')
    for r in resources:
        rid=r.get('resource_id')
        if rid not in declared: issues.append('MANIFEST_RESOURCE_MISSING')
        if r.get('manifest_digest')!=r.get('payload_digest'): issues.append('DIGEST_MISMATCH')
        if not r.get('rights_ref') or not r.get('provenance_ref'): issues.append('RIGHTS_OR_PROVENANCE_MISSING')
        for dep in r.get('dependencies') or []:
            if dep not in rm or dep not in declared: issues.append('DEPENDENCY_MISSING')
    for rid in declared:
        if rid not in rm: issues.append('DECLARED_RESOURCE_MISSING')
    im={i.get('source_resource_id'):i for i in imports}
    cap=set(target.get('capabilities') or []); migrations=target.get('migration_rules') or {}
    for rid,r in rm.items():
        i=im.get(rid)
        if not i: issues.append('IMPORT_EVIDENCE_MISSING'); continue
        if i.get('result_resource_id')!=rid: issues.append('RESOURCE_ID_REWRITTEN')
        supported=r.get('required_capability') in cap
        if not supported:
            if i.get('flattened') or i.get('compatibility_state')=='IMPORT_COMPATIBLE': issues.append('SILENT_FLATTENING')
            if i.get('compatibility_state')=='MIGRATION_REQUIRED':
                ref=i.get('migration_rule_ref')
                if not ref or migrations.get(r.get('required_capability'))!=ref: issues.append('MIGRATION_RULE_MISSING')
            elif not i.get('quarantined') or not i.get('quarantine_reason'): issues.append('UNSUPPORTED_NOT_QUARANTINED')
        else:
            if i.get('compatibility_state') not in {'IMPORT_COMPATIBLE','MIGRATION_REQUIRED'}: issues.append('SUPPORTED_RESOURCE_STATE_INVALID')
    rtmap={x.get('resource_id'):x for x in rt}
    for rid,r in rm.items():
        i=im.get(rid) or {}; x=rtmap.get(rid)
        if not x: issues.append('ROUND_TRIP_EVIDENCE_MISSING'); continue
        if i.get('quarantined'):
            if x.get('semantic_diff_state')!='NOT_IMPORTED_QUARANTINED': issues.append('QUARANTINE_ROUND_TRIP_STATE_INVALID')
        else:
            if x.get('baseline_semantic_digest')!=r.get('semantic_digest'): issues.append('ROUND_TRIP_BASELINE_BINDING_MISMATCH')
            if not x.get('result_semantic_digest'): issues.append('ROUND_TRIP_EVIDENCE_MISSING')
    if not review.get('owner') or not review.get('audit_event_id'): issues.append('REVIEW_EVIDENCE_MISSING')
    return sorted(set(issues))

def expected_decision(f):
    issues=set(inspect(f))
    blockers={'INPUT_INVALID','PACKAGE_EVIDENCE_MISSING','MANIFEST_RESOURCE_MISSING','DIGEST_MISMATCH','RIGHTS_OR_PROVENANCE_MISSING','DEPENDENCY_MISSING','DECLARED_RESOURCE_MISSING','IMPORT_EVIDENCE_MISSING','RESOURCE_ID_REWRITTEN','SILENT_FLATTENING','MIGRATION_RULE_MISSING','UNSUPPORTED_NOT_QUARANTINED','SUPPORTED_RESOURCE_STATE_INVALID','ROUND_TRIP_EVIDENCE_MISSING','QUARANTINE_ROUND_TRIP_STATE_INVALID','ROUND_TRIP_BASELINE_BINDING_MISMATCH','REVIEW_EVIDENCE_MISSING'}
    if issues & blockers: return 'HOLD'
    for x in (f.get('round_trip') or {}).get('resources') or []:
        if str(x.get('semantic_diff_state','')).startswith('CHANGED'): return 'REVIEW_REQUIRED'
    if any(i.get('quarantined') or i.get('compatibility_state')=='MIGRATION_REQUIRED' for i in (f.get('import_result') or [])): return 'REVIEW_REQUIRED'
    if (f.get('review') or {}).get('state')!='APPROVED': return 'REVIEW_REQUIRED'
    return 'IMPORT_ACCEPTABLE_BOUNDED'
