"""Versioned protocol after complete payload validation; no damaged frame becomes negative."""
from __future__ import annotations
from collections import Counter
from pathlib import Path
import json
import shutil

from .protocol import load_protocol,file_digest,write_json


def quarantine(source='outputs/protocol_v4',destination='outputs/protocol_v5',
               audit='outputs/payload_audit_v4/summary.json'):
    source=Path(source);destination=Path(destination)
    if (destination/'protocol.json').exists():return load_protocol(destination)[2]
    records,assignments,parent=load_protocol(source)
    report=json.loads(Path(audit).read_text())
    if not report['complete'] or report['expected_frames']!=len(records) or report['protocol_sha256']!=file_digest(source/'protocol.json'):
        raise ValueError('quarantine requires a complete matching raw-payload audit')
    failures={r['frame_id'] for r in report['failures']}
    if not failures:raise ValueError('no damaged source frames requiring quarantine')
    destination.mkdir(parents=True,exist_ok=True)
    for name in ('sensors.json','content_hashes.json','splits.json','migration.json'):
        shutil.copyfile(source/name,destination/name)
    rows=[json.loads(line) for line in (source/'manifest.jsonl').read_text().splitlines()]
    retained=[row for row in rows if row['frame_id'] not in failures]
    with (destination/'manifest.jsonl').open('w') as stream:
        for row in retained:stream.write(json.dumps(row,sort_keys=True)+'\n')
    excluded=json.loads((source/'excluded.json').read_text())
    for row in rows:
        if row['frame_id'] in failures:excluded.append({'frame_id':row['frame_id'],
            'reason':'Full payload validation failed; never treat as an empty scene',
            'source_sha256':row['source_sha256'],'record':row})
    write_json(destination/'excluded.json',excluded)
    pilot=json.loads((source/'pilot.json').read_text())
    mapping={'train':[],'val':[],'test':[]}
    for split,items in pilot.items():
        mapping[split]=[fid for fid in items if fid not in failures]
        removed=len(items)-len(mapping[split])
        if removed:
            existing=set().union(*(set(v) for v in pilot.values()))
            fallback=[row['frame_id'] for row in retained if row['split']==split and row['frame_id'] not in existing]
            if len(fallback)<removed:raise ValueError('not enough replacement source frames')
            mapping[split]+=fallback[:removed]
    write_json(destination/'pilot.json',mapping)
    migration={'parent_protocol_sha256':file_digest(source/'protocol.json'),
               'payload_audit_sha256':file_digest(audit),
               'payload_audit_index_sha256':report['validity_index_sha256'],
               'reason':'Remove fully decoded PCD corruption discovered after header-only inventory',
               'quarantined_frame_ids':sorted(failures),'old_pilot_replacements':{
                   s:[x for x in mapping[s] if x not in pilot[s]] for s in mapping}}
    write_json(destination/'quarantine.json',migration)
    revised={**parent,'version':5,'parent_protocol_sha256':migration['parent_protocol_sha256'],
             'files':{name:file_digest(destination/name) for name in
                      ['manifest.jsonl','splits.json','sensors.json','content_hashes.json','pilot.json','excluded.json','migration.json','quarantine.json']},
             'frames':len(retained),'excluded':len(excluded),'payload_validity_index_sha256':report['validity_index_sha256'],
             'split_counts':dict(Counter(row['split'] for row in retained))}
    write_json(destination/'protocol.json',revised)
    return revised


if __name__=='__main__':print(json.dumps(quarantine()))
