#!/usr/bin/env python3
"""
Assemble the human_eval deliverables from _results.json (produced by
batch_process.py):

    clips/clip01.mp4 ... clip30.mp4   the video clips, renamed
    predictions.csv                    clip_id + 4 system predictions (rater-facing)
    predictions.json                   full per-clip detail (drives /evaluation page)
    manifest.csv                       clip_id -> source clip / breed / duration
    sheet.csv                          blank 30x2 scoring sheet (A & B pre-filled)

Re-run any time; it is deterministic and overwrites its outputs.
"""
import os, json, csv, shutil

HERE = os.path.dirname(os.path.abspath(__file__))
N = 30

results = json.load(open(os.path.join(HERE, '_results.json')))
usable = [r for r in results if r.get('ok')][:N]
if len(usable) < N:
    print(f'WARNING: only {len(usable)} usable clips (< {N}). '
          f'Building with what is available.')

clips_dir = os.path.join(HERE, 'clips')
os.makedirs(clips_dir, exist_ok=True)

pred_rows, pred_json, manifest_rows = [], [], []
for i, r in enumerate(usable, 1):
    cid = f'clip{i:02d}'
    dst = os.path.join(clips_dir, cid + '.mp4')
    shutil.copy(r['clip_path'], dst)

    pred_rows.append({
        'clip_id': cid,
        'environment': r['environment'],
        'activity': r['activity'],
        'intention': r['intention'],
        'interpretation': r['interpretation'],
    })
    pred_json.append({
        'clip_id': cid,
        'video': f'clips/{cid}.mp4',
        'environment': r['environment'],
        'activity': r['activity'],
        'intention': r['intention'],
        'interpretation': r['interpretation'],
        'dominant_themes': r.get('dominant_themes', []),
        'detected_words': r.get('detected_words', []),
        'breed': r['breed'],
        'duration': r['duration'],
        'n_sentences': r['n_sentences'],
        'source_key': r['key'],
    })
    manifest_rows.append({
        'clip_id': cid, 'source_key': r['key'], 'breed': r['breed'],
        'duration': r['duration'], 'video_id': r['video_id'],
        'n_sentences': r['n_sentences'], 'n_phones': r['n_phones'],
    })

def write_csv(path, rows, fields):
    with open(path, 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        w.writerows(rows)

write_csv(os.path.join(HERE, 'predictions.csv'), pred_rows,
          ['clip_id', 'environment', 'activity', 'intention', 'interpretation'])
write_csv(os.path.join(HERE, 'manifest.csv'), manifest_rows,
          ['clip_id', 'source_key', 'breed', 'duration', 'video_id',
           'n_sentences', 'n_phones'])
json.dump(pred_json, open(os.path.join(HERE, 'predictions.json'), 'w'), indent=1)

# Blank scoring sheet: one row per clip per annotator.
sheet = []
for r in pred_rows:
    for ann in ('A', 'B'):
        sheet.append({'clip_id': r['clip_id'], 'annotator': ann,
                      'environment': '', 'activity': '', 'intention': '',
                      'interpretation': '', 'notes': ''})
write_csv(os.path.join(HERE, 'sheet.csv'), sheet,
          ['clip_id', 'annotator', 'environment', 'activity', 'intention',
           'interpretation', 'notes'])

print(f'Built {len(pred_rows)} clips -> clips/, predictions.csv/.json, '
      f'manifest.csv, sheet.csv ({len(sheet)} rows).')
