"""Join full file inventory with actual canonical-payload verification."""
from pathlib import Path
import json
from .protocol import write_json,file_digest


def reconcile():
    root=Path('/root/private/data/pallet')
    inventory=json.loads(Path('outputs/inventory_v3/summary.json').read_text())
    payload=json.loads(Path('outputs/payload_audit_v4/summary.json').read_text())
    records=[]
    for relative in inventory['non_timestamp_pcd_candidates']:
        path=root/relative
        if any(word in path.name for word in ('transformed','segmentation','section')):
            reason='Derived or segmented cloud without an independently recoverable capture identity; retain as evidence, exclude from frame count.'
        else:
            reason='Missing timestamp/capture lineage; independent-scene membership cannot be established without risking leakage.'
        records.append({'path':str(path),'sha256':file_digest(path),'disposition':'quarantine_capture_lineage',
                        'reason':reason,'negative_example':False})
    for row in payload['failures']:
        records.append({'path':row['pcd'],'sha256':row['source_sha256'],'disposition':'damaged_payload',
                        'reason':row['error'],'negative_example':False})
    for row in map(json.loads,Path('outputs/inventory_v3/unique_sensor_records.jsonl').read_text().splitlines()):
        records.append({'archive_sensor':row,'disposition':'quarantine_partial_unorganized_cloud',
                        'reason':'Only unique archived sensor is a sparse section; cannot infer an image grid or independent capture.'})
    report={'inventory_sha256':file_digest('outputs/inventory_v3/summary.json'),
            'payload_audit_sha256':file_digest('outputs/payload_audit_v4/summary.json'),
            'disk_files':inventory['files'],'archive_members':inventory['archive_member_rows'],
            'valid_canonical_frames':payload['valid'],'canonical_payload_corruption':len(payload['failures']),
            'non_timestamped_sensor_dispositions':records,
            'note':'Quarantine is an evidence-based exclusion, not a fabricated negative or reviewed pallet label.'}
    write_json('outputs/reconciliation_v5.json',report)
    return report


if __name__=='__main__':r=reconcile();print('reconciled exceptional sensor items:',len(r['non_timestamped_sensor_dispositions']))
