#!/usr/bin/env bash
# Pull Charlie Hoffman's published Record-to-Report instance package
# (the validation reference) from xbrlsite.com into
# local/datasets/seattle_method/report/ (gitignored).
#
# Authoritative upstream:
#   http://www.xbrlsite.com/seattlemethod/platinum-testcases/record-to-report/
#
# Contents of report.zip:
#   - instance.xml             — the XBRL instance document (133 facts, 93
#                                concepts) generated by luca.auditchain.finance
#                                from the 14 JE lemonade-stand dataset
#   - report.xsd               — taxonomy schema referenced by instance.xml
#   - report-{pre,cal,def,lab,for,ref}.xml — linkbases
#   - ixbrl-report-viewer.html + ixbrlviewer.js — Charlie's iXBRL viewer
#
# The reconciliation harness (reconcile.py) parses instance.xml as the
# source of truth — strictly stronger validation than the earlier
# hand-extracted CSV fixture. Idempotent — re-runs overwrite the local copy.

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
OUT_DIR="$REPO_ROOT/local/datasets/seattle_method/report"
ZIP_PATH="$OUT_DIR/report.zip"

URL="http://www.xbrlsite.com/seattlemethod/platinum-testcases/record-to-report/report.zip"

mkdir -p "$OUT_DIR"

echo "Pulling report.zip → $OUT_DIR"

if curl -fsSL "$URL" -o "$ZIP_PATH"; then
  echo "  ✓ report.zip ($(wc -c < "$ZIP_PATH" | tr -d ' ') bytes)"
else
  echo "  ✗ report.zip (required — aborting)" >&2
  exit 1
fi

echo "Unzipping → $OUT_DIR"
# -o overwrite, -q quiet
unzip -oq "$ZIP_PATH" -d "$OUT_DIR"

if [ ! -f "$OUT_DIR/instance.xml" ]; then
  echo "  ✗ instance.xml missing after unzip — aborting" >&2
  exit 1
fi

instance_lines=$(wc -l < "$OUT_DIR/instance.xml" | tr -d ' ')
echo "  ✓ instance.xml ($instance_lines lines)"

# Clean up the zip — keep only the extracted files.
rm -f "$ZIP_PATH"

echo
echo "Files:"
ls "$OUT_DIR" | sed 's/^/  /'
echo
echo "Next: uv run python -m examples.seattle_method_demo.reconcile"
