#!/usr/bin/env bash
set -euo pipefail

BASE="${1:-/mnt/bigstor/www/usecases}"
cd "$BASE"

MAPPER="build_r155_review_mapping_v3_2_1.py"
GENERATOR="build_r155_test_pages_v2_3.py"
REGDIR="regulatory/r155"
STAGED="$REGDIR/r155_threat_mappings_v3_2.json"
LIVE="$REGDIR/r155_threat_mappings.json"
BASELINE="$REGDIR/r155_threat_mappings_baseline_v3_2_1.json"
MANIFEST="$REGDIR/baseline_v3_2_1.json"

for f in "$MAPPER" "$GENERATOR" "$STAGED"; do
  [[ -f "$f" ]] || { echo "ERROR: missing $f" >&2; exit 2; }
done

python3 -m py_compile "$MAPPER" "$GENERATOR"
python3 -m json.tool "$STAGED" >/dev/null

schema="$(jq -r '.schema_version // empty' "$STAGED")"
setid="$(jq -r '.mapping_set_id // empty' "$STAGED")"
status="$(jq -r '.status // empty' "$STAGED")"
accepted="$(jq -r 'if .rules | has("accepted_created") then (.rules.accepted_created | tostring) else "missing" end' "$STAGED")"
legal="$(jq -r 'if .rules | has("legal_compliance_inference") then (.rules.legal_compliance_inference | tostring) else "missing" end' "$STAGED")"

[[ "$schema" == "2.2.1" ]] || { echo "ERROR: expected schema_version 2.2.1, got $schema" >&2; exit 2; }
[[ "$setid" == "NCRC-R155-REVIEW-3.2.1" ]] || { echo "ERROR: unexpected mapping_set_id: $setid" >&2; exit 2; }
[[ "$status" == "review" ]] || { echo "ERROR: baseline must remain review, got $status" >&2; exit 2; }
[[ "$accepted" == "false" ]] || { echo "ERROR: accepted_created must remain false" >&2; exit 2; }
[[ "$legal" == "false" ]] || { echo "ERROR: legal_compliance_inference must remain false" >&2; exit 2; }

# Preserve any previous live mapping once. Do not overwrite historical backups.
if [[ -f "$LIVE" ]]; then
  old_sha="$(sha256sum "$LIVE" | awk '{print $1}')"
  backup="$REGDIR/r155_threat_mappings.pre_v3_2_1.${old_sha:0:12}.json"
  [[ -f "$backup" ]] || cp -a "$LIVE" "$backup"
fi

cp -a "$STAGED" "$BASELINE"
cp -a "$BASELINE" "$LIVE"

mapper_sha="$(sha256sum "$MAPPER" | awk '{print $1}')"
generator_sha="$(sha256sum "$GENERATOR" | awk '{print $1}')"
mapping_sha="$(sha256sum "$BASELINE" | awk '{print $1}')"
threat_sha="$(sha256sum data/threats_register.json | awk '{print $1}')"
annex_sha="$(sha256sum "$REGDIR/annex5.json" | awk '{print $1}')"

jq -n \
  --arg baseline_id "NCRC-R155-BASELINE-3.2.1" \
  --arg status "review_baseline" \
  --arg mapper "$MAPPER" \
  --arg mapper_sha "$mapper_sha" \
  --arg generator "$GENERATOR" \
  --arg generator_sha "$generator_sha" \
  --arg mapping "$BASELINE" \
  --arg mapping_sha "$mapping_sha" \
  --arg live "$LIVE" \
  --arg threat_register "data/threats_register.json" \
  --arg threat_sha "$threat_sha" \
  --arg annex5 "$REGDIR/annex5.json" \
  --arg annex_sha "$annex_sha" \
  --argjson summary "$(jq '.summary' "$BASELINE")" \
  '{
    baseline_id: $baseline_id,
    status: $status,
    purpose: "Baseline for independent expert review; not a compliance determination.",
    expert_review_required: true,
    recommended_independent_expert_reviews: 3,
    immutable_inputs: {
      mapper: {file: $mapper, sha256: $mapper_sha},
      page_generator: {file: $generator, sha256: $generator_sha},
      mapping_snapshot: {file: $mapping, sha256: $mapping_sha},
      threat_register: {file: $threat_register, sha256: $threat_sha},
      annex5: {file: $annex5, sha256: $annex_sha}
    },
    promoted_live_mapping: $live,
    summary: $summary,
    review_policy: {
      mapping_decisions: ["keep", "reject", "uncertain"],
      relationship_strength: ["direct", "indirect", "consequence"],
      coverage_decisions: ["complete", "undermapped", "no_direct_mapping_expected"],
      preserve_individual_reviews: true,
      mapper_changes_after_baseline: "Only through a new versioned baseline after expert review evidence."
    }
  }' > "$MANIFEST"
python3 -m json.tool "$MANIFEST" >/dev/null

# Validate the promoted live baseline, not an older mapping snapshot.
python3 "$REGDIR/validate_r155.py" "$REGDIR" --threat-register data/threats_register.json

# Rebuild test copies from the promoted live mapping. Validator was already run above.
python3 "$GENERATOR" --mapping-file "$LIVE" --skip-validation

printf '\nBASELINE PROMOTED\n'
printf '  live mapping : %s\n' "$LIVE"
printf '  snapshot     : %s\n' "$BASELINE"
printf '  manifest     : %s\n' "$MANIFEST"
printf '  mapping sha  : %s\n' "$mapping_sha"
printf '\nSummary:\n'
jq '.summary' "$BASELINE"
