#!/usr/bin/env bash
# Run from the project checkout. A pending review attestation prevents training.
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd -- "$project_dir"
export PYTHONPATH="$project_dir${PYTHONPATH:+:$PYTHONPATH}"
config="${PALLET_ASSISTANT_CONFIG:-configs/human_correction_1716_accelerated.json}"
output="${PALLET_ASSISTANT_OUTPUT:-outputs/human_correction_manual_1716_v2}"
protocol="outputs/protocol_v5"
source_export="outputs/anylabeling/pallet_v5_20260930"
device="GPU-3ce8e1e7-efb2-80a6-de52-75da2f9fa259"

.venv/bin/python - "$config" <<'PY'
import hashlib, json, pathlib, shutil, sys
config = json.loads(pathlib.Path(sys.argv[1]).read_text())
for key in ('all_frames_reviewed_by_user',
            'unchanged_proposals_accepted_after_manual_review',
            'empty_frames_confirmed_negative_by_user'):
    if config.get(key) is not True:
        raise SystemExit('Review scope awaits user confirmation: ' + key)
if config['review_attestation'].startswith('pending_'):
    raise SystemExit('Review attestation must record the actual user confirmation.')
for source in config['sources'] + [config['historical_comparison']]:
    path = pathlib.Path(source['archive'])
    if hashlib.sha256(path.read_bytes()).hexdigest() != source['archive_sha256']:
        raise SystemExit('Correction archive changed: ' + str(path))
comparison = config['historical_comparison']
if hashlib.sha256(pathlib.Path(comparison['preflight_path']).read_bytes()).hexdigest() != comparison['preflight_sha256']:
    raise SystemExit('Historical comparison report changed.')
if shutil.disk_usage('.').free < 50 * 2**30:
    raise SystemExit('Below 50 GiB disk reserve.')
PY

log_dir="outputs/manual_1410_preflight/accelerated_workflow_logs"
mkdir -p -- "$log_dir"
run_stage() {
  local stage="$1"
  shift
  .venv/bin/python -m pallet.human_labeling "$stage" "$@" 2>&1 | tee "$log_dir/$stage.log"
}
run_stage import-manual --corrections-config "$config" --output "$output" --protocol "$protocol"
run_stage partition --source-output "$output" --output "$output" --protocol "$protocol" --seed 42 --validation-fraction 0.15
.venv/bin/python - "$output" <<'PY'
import json, pathlib, sys
current = json.loads((pathlib.Path(sys.argv[1]) / 'manual_partition.json').read_text())
prior = json.loads(pathlib.Path('outputs/human_correction_manual_1716_v1/manual_partition.json').read_text())
for key in ('manual_annotations_sha256', 'train_frame_ids', 'validation_frame_ids',
            'train_groups', 'validation_groups', 'status_counts', 'positive_boxes'):
    if current[key] != prior[key]:
        raise SystemExit('Acceleration changed frozen labels/split: ' + key)
PY
run_stage train-manual --output "$output" --protocol "$protocol" --root /root/private/data/pallet --device "$device" --epochs 300 --batch-size 16 --workers 4 --validation-batch-size 16
run_stage calibrate --output "$output" --protocol "$protocol" --root /root/private/data/pallet --device "$device"
run_stage predict --output "$output" --protocol "$protocol" --root /root/private/data/pallet --source-export "$source_export" --device "$device" --batch-size 4
run_stage package --output "$output" --protocol "$protocol" --source-export "$source_export"
