#!/usr/bin/env bash
set -Eeuo pipefail
umask 077

STEP_ID="STEP_050M07R13G4_FIX_FIND_OR_ACCESS_MAP_ROTATION"
RESULT_PASS="PASS_STEP_050M07R13G4_FIX_FIND_OR_ACCESS_MAP_ROTATION"

BASE="/opt/router-ops"
BIN="$BASE/bin"
TOKEN="e94a0859747d7b96f29c7fdafc2d0351ba603bb0a7e9e5a4"
ROOT="$BASE/public/r/$TOKEN"
LATEST="$ROOT/latest"
OLD="$ROOT/old"

TUNNEL_BASE="${TUNNEL_BASE:?TUNNEL_BASE is required}"
BASE_URL="$TUNNEL_BASE/r/$TOKEN"
LATEST_ROOT_URL="$BASE_URL/latest/"
OLD_ROOT_URL="$BASE_URL/old/"

PUBLISHER="$BIN/router-publish-report"
REINDEX="$BIN/router-public-reindex"

TS="$(date -u +%Y%m%d-%H%M%S)"
STATE="$BASE/state/access-map-find-or-fix/$TS"
BACKUP="$STATE/backup"
REPORT_BUILD="$STATE/report-build"
PROGRESS="$STATE/progress.log"

mkdir -p "$BACKUP" "$REPORT_BUILD"
chmod 700 "$STATE" "$BACKUP" "$REPORT_BUILD"
exec > >(tee -a "$PROGRESS") 2>&1

phase() { printf '>>> [%s] %s\n' "$1" "$2"; }

fail() {
    local reason="$1"
    printf '\nRESULT=STOP_%s\n' "$STEP_ID"
    printf 'FAILURE_REASON=%s\n' "$reason"
    printf 'STATE_DIR=%s\n' "$STATE"
    exit 1
}

trap 'rc=$?; fail "COMMAND_FAILED_RC_${rc}_LINE_${LINENO}"' ERR

single_latest_name() {
    local pattern="$1"
    local -a matches=()
    mapfile -t matches < <(
        find "$LATEST" -mindepth 1 -maxdepth 1 -type d \
            -name "$pattern" -printf '%f\n' | LC_ALL=C sort
    )
    [ "${#matches[@]}" -eq 1 ]
    printf '%s\n' "${matches[0]}"
}

phase PREFLIGHT "checking current broken matcher and duplicate Access Map folders"

test -x "$PUBLISHER"
test -x "$REINDEX"

grep -Fq \
  'xs_map_*|access_map_*) KIND="access-map"; MATCH='\''*_xs_map_*|*_access_map_*'\'' ;;' \
  "$PUBLISHER"

mapfile -t BEFORE_ACCESS_DIRS < <(
    find "$LATEST" -mindepth 1 -maxdepth 1 -type d \
        \( -name '*_xs_map_*' -o -name '*_access_map_*' \) \
        -printf '%f\n' | LC_ALL=C sort
)

[ "${#BEFORE_ACCESS_DIRS[@]}" -ge 3 ]
printf '%s\n' "${BEFORE_ACCESS_DIRS[@]}" > "$STATE/access-map-latest-before.txt"

cp -a "$PUBLISHER" "$BACKUP/router-publish-report"

phase PATCH "replacing literal pipe matcher with a real find OR expression"

python3 - "$PUBLISHER" <<'PY'
from pathlib import Path
import sys

path = Path(sys.argv[1])
text = path.read_text()

old_case = '  xs_map_*|access_map_*) KIND="access-map"; MATCH=\'*_xs_map_*|*_access_map_*\' ;;'
new_case = '  xs_map_*|access_map_*) KIND="access-map"; MATCH=\'access-map-special\' ;;'

old_find = "find \"$LATEST\" \\\n  -mindepth 1 \\\n  -maxdepth 1 \\\n  -type d \\\n  -name \"$MATCH\" \\\n  -printf '%f\\n' |"

new_find = "if [ \"$KIND\" = \"access-map\" ]; then\n  find \"$LATEST\" \\\n    -mindepth 1 \\\n    -maxdepth 1 \\\n    -type d \\\n    \\( -name '*_xs_map_*' -o -name '*_access_map_*' \\) \\\n    -printf '%f\\n'\nelse\n  find \"$LATEST\" \\\n    -mindepth 1 \\\n    -maxdepth 1 \\\n    -type d \\\n    -name \"$MATCH\" \\\n    -printf '%f\\n'\nfi |"

if text.count(old_case) != 1:
    raise SystemExit("broken access-map case line not found exactly once")
if text.count(old_find) != 1:
    raise SystemExit("generic find block not found exactly once")

text = text.replace(old_case, new_case)
text = text.replace(old_find, new_find)
path.write_text(text)
PY

chmod 0755 "$PUBLISHER"
sh -n "$PUBLISHER"

grep -Fq 'KIND="access-map"; MATCH='\''access-map-special'\''' "$PUBLISHER"
grep -Fq "\\( -name '*_xs_map_*' -o -name '*_access_map_*' \\)" "$PUBLISHER"

phase PUBLISH_TEST "publishing final canonical Access Map through corrected matcher"

SOURCE_DIR="$LATEST/20260714-092041_access_map_canonical_final"
test -d "$SOURCE_DIR"
test -f "$SOURCE_DIR/access-map.md"

ACCESS_OUTPUT="$(
    TUNNEL_BASE="$TUNNEL_BASE" \
    "$PUBLISHER" \
        access_map_canonical_current \
        "$SOURCE_DIR/access-map.md" \
        "$SOURCE_DIR/report.txt" \
        "$SOURCE_DIR/facts.json" \
        "$SOURCE_DIR/verify.txt" \
        "$SOURCE_DIR/rollback.sh"
)"

printf '%s\n' "$ACCESS_OUTPUT" | tee "$STATE/access-map-publish-output.txt"

ACCESS_MAP_URL="$(printf '%s\n' "$ACCESS_OUTPUT" | sed -n 's/^TRYCF_REPORT=//p' | tail -n 1)"
ACCESS_DIR="$(printf '%s\n' "$ACCESS_OUTPUT" | sed -n 's/^PUBLISHED_DIR=//p' | tail -n 1)"
PREVIOUS_MOVED_COUNT="$(printf '%s\n' "$ACCESS_OUTPUT" | sed -n 's/^PREVIOUS_MOVED_COUNT=//p' | tail -n 1)"

test -n "$ACCESS_MAP_URL"
test -d "$ACCESS_DIR"
[ "$PREVIOUS_MOVED_COUNT" -ge 3 ]

mapfile -t AFTER_ACCESS_DIRS < <(
    find "$LATEST" -mindepth 1 -maxdepth 1 -type d \
        \( -name '*_xs_map_*' -o -name '*_access_map_*' \) \
        -printf '%f\n' | LC_ALL=C sort
)

[ "${#AFTER_ACCESS_DIRS[@]}" -eq 1 ]
printf '%s\n' "${AFTER_ACCESS_DIRS[@]}" > "$STATE/access-map-latest-after.txt"

if grep -RniE --exclude='step-code.sh' '(XS Map|XS map|xs-map|XS_MAP|xs_map)' "$ACCESS_DIR"; then
    fail "LEGACY_NAMING_REMAINS_IN_FINAL_ACCESS_MAP"
fi

curl -fsS --max-time 30 "$ACCESS_MAP_URL" >/dev/null
curl -fsS --max-time 30 "${ACCESS_MAP_URL}access-map.md" >/dev/null
curl -fsS --max-time 30 "${ACCESS_MAP_URL}report.txt" >/dev/null
curl -fsS --max-time 30 "${ACCESS_MAP_URL}facts.json" >/dev/null
curl -fsS --max-time 30 "${ACCESS_MAP_URL}verify.txt" >/dev/null

phase LINKS "resolving current canonical links"

LOCAL_M07_NAME="$(single_latest_name '*_local_architecture_plan_vm101_autonomous_hmn_recovery*')"
GLOBAL_PLAN_NAME="$(single_latest_name '*_global_project_plan_wg_paid*')"
VM100_NAME="$(single_latest_name '*_vm100_git_source_*')"
VM101_NAME="$(single_latest_name '*_vm101_git_source_*')"
VM121_NAME="$(single_latest_name '*_vm121_git_source_*')"
VM101_MODEL_NAME="$(single_latest_name '*_vm101_model_*')"
VM101_METHODS_NAME="$(single_latest_name '*_vm101_methods_*')"
VM130_SOURCE_NAME="$(single_latest_name '*_vm130_router_ops_source_snapshot_*')"

LOCAL_M07_PLAN_URL="$LATEST_ROOT_URL$LOCAL_M07_NAME/"
GLOBAL_PROJECT_PLAN_URL="$LATEST_ROOT_URL$GLOBAL_PLAN_NAME/"
VM100_PUBLIC_URL="$LATEST_ROOT_URL$VM100_NAME/"
VM101_PUBLIC_URL="$LATEST_ROOT_URL$VM101_NAME/"
VM121_PUBLIC_URL="$LATEST_ROOT_URL$VM121_NAME/"
VM101_MODEL_URL="$LATEST_ROOT_URL$VM101_MODEL_NAME/vm101-model.txt"
VM101_METHODS_URL="$LATEST_ROOT_URL$VM101_METHODS_NAME/"
VM130_SOURCE_URL="$LATEST_ROOT_URL$VM130_SOURCE_NAME/"
ARCHITECTURE_PLAN_URL="$LOCAL_M07_PLAN_URL"

phase REPORT "building formal STEP report"

cp "$0" "$REPORT_BUILD/step-code.sh"
cp "$PROGRESS" "$REPORT_BUILD/progress.log"
cp "$STATE/access-map-publish-output.txt" "$REPORT_BUILD/access-map-publish-output.txt"
cp "$STATE/access-map-latest-before.txt" "$REPORT_BUILD/access-map-latest-before.txt"
cp "$STATE/access-map-latest-after.txt" "$REPORT_BUILD/access-map-latest-after.txt"
cp "$PUBLISHER" "$REPORT_BUILD/router-publish-report.after"
cp "$BACKUP/router-publish-report" "$REPORT_BUILD/router-publish-report.before"

cat > "$REPORT_BUILD/report.txt" <<EOF_REPORT
RESULT=$RESULT_PASS
STEP=$STEP_ID
TIMESTAMP_UTC=$TS
ROOT_CAUSE=find -name treated pipe as a literal character
PUBLISHER_FIX=explicit find OR expression for xs_map and access_map
PREVIOUS_MOVED_COUNT=$PREVIOUS_MOVED_COUNT
ACCESS_MAP_LATEST_COUNT_BEFORE=${#BEFORE_ACCESS_DIRS[@]}
ACCESS_MAP_LATEST_COUNT_AFTER=${#AFTER_ACCESS_DIRS[@]}
EXACTLY_ONE_ACCESS_MAP_IN_LATEST=true
LEGACY_NAMING_PRESENT_IN_FINAL=false
HTTP_VERIFY=true
PUBLICATION_CODE_CHANGED=true
ACCESS_MAP_CHANGED=true
VM100_CHANGED=false
VM101_CHANGED=false
VM121_CHANGED=false
VM130_RUNTIME_CHANGED=false
RUNTIME_IMPACT=false
ROLLBACK_AVAILABLE=true
EOF_REPORT

python3 - "$REPORT_BUILD/facts.json" <<PY
import json
from pathlib import Path
facts = {
    "step_id": "$STEP_ID",
    "result": "$RESULT_PASS",
    "timestamp_utc": "$TS",
    "root_cause": "find -name treated pipe as a literal character",
    "publisher_fix": "explicit find OR expression for xs_map and access_map",
    "previous_moved_count": int("$PREVIOUS_MOVED_COUNT"),
    "access_map_latest_count_before": ${#BEFORE_ACCESS_DIRS[@]},
    "access_map_latest_count_after": ${#AFTER_ACCESS_DIRS[@]},
    "exactly_one_access_map_in_latest": True,
    "legacy_naming_present_in_final": False,
    "http_verify": True,
    "publication_code_changed": True,
    "access_map_changed": True,
    "vm100_changed": False,
    "vm101_changed": False,
    "vm121_changed": False,
    "vm130_runtime_changed": False,
    "runtime_impact": False,
    "access_map_url": "$ACCESS_MAP_URL"
}
Path("$REPORT_BUILD/facts.json").write_text(json.dumps(facts, indent=2) + "\n")
PY

cat > "$REPORT_BUILD/verify.txt" <<EOF_VERIFY
RESULT=PASS
ROOT_CAUSE_CONFIRMED=true
FIND_LITERAL_PIPE_BUG_FIXED=true
MATCHES_LEGACY_XS_MAP=true
MATCHES_CANONICAL_ACCESS_MAP=true
PREVIOUS_MOVED_COUNT=$PREVIOUS_MOVED_COUNT
ACCESS_MAP_LATEST_COUNT_BEFORE=${#BEFORE_ACCESS_DIRS[@]}
ACCESS_MAP_LATEST_COUNT_AFTER=${#AFTER_ACCESS_DIRS[@]}
EXACTLY_ONE_ACCESS_MAP_IN_LATEST=true
LEGACY_NAMING_PRESENT_IN_FINAL=false
HTTP_VERIFY=true
PUBLICATION_CODE_CHANGED=true
VM100_CHANGED=false
VM101_CHANGED=false
VM121_CHANGED=false
VM130_RUNTIME_CHANGED=false
RUNTIME_IMPACT=false
EOF_VERIFY

cat > "$REPORT_BUILD/rollback.sh" <<EOF_ROLLBACK
#!/usr/bin/env bash
set -Eeuo pipefail
cp -a "$BACKUP/router-publish-report" "$PUBLISHER"
chmod 0755 "$PUBLISHER"
sh -n "$PUBLISHER"
echo "RESULT=PASS_ROLLBACK_$STEP_ID"
EOF_ROLLBACK
chmod 0755 "$REPORT_BUILD/rollback.sh"

phase PUBLISH_REPORT "publishing STEP report"

REPORT_OUTPUT="$(
    TUNNEL_BASE="$TUNNEL_BASE" \
    "$PUBLISHER" \
        step050m07r13g4_fix_find_or_access_map_rotation \
        "$REPORT_BUILD/step-code.sh" \
        "$REPORT_BUILD/report.txt" \
        "$REPORT_BUILD/facts.json" \
        "$REPORT_BUILD/progress.log" \
        "$REPORT_BUILD/verify.txt" \
        "$REPORT_BUILD/rollback.sh" \
        "$REPORT_BUILD/access-map-publish-output.txt" \
        "$REPORT_BUILD/access-map-latest-before.txt" \
        "$REPORT_BUILD/access-map-latest-after.txt" \
        "$REPORT_BUILD/router-publish-report.before" \
        "$REPORT_BUILD/router-publish-report.after"
)"

printf '%s\n' "$REPORT_OUTPUT" | tee "$STATE/report-publish-output.txt"
STEP_REPORT_URL="$(printf '%s\n' "$REPORT_OUTPUT" | sed -n 's/^TRYCF_REPORT=//p' | tail -n 1)"
test -n "$STEP_REPORT_URL"

curl -fsS --max-time 30 "$STEP_REPORT_URL" >/dev/null
curl -fsS --max-time 30 "${STEP_REPORT_URL}report.txt" >/dev/null
curl -fsS --max-time 30 "${STEP_REPORT_URL}facts.json" >/dev/null
curl -fsS --max-time 30 "${STEP_REPORT_URL}verify.txt" >/dev/null
curl -fsS --max-time 30 "${STEP_REPORT_URL}step-code.sh" >/dev/null

printf '\nRESULT=%s\n' "$RESULT_PASS"
printf 'STEP_REPORT_URL=%s\n' "$STEP_REPORT_URL"
printf 'LATEST_ROOT_URL=%s\n' "$LATEST_ROOT_URL"
printf 'OLD_ROOT_URL=%s\n' "$OLD_ROOT_URL"
printf 'LOCAL_M07_PLAN_URL=%s\n' "$LOCAL_M07_PLAN_URL"
printf 'GLOBAL_PROJECT_PLAN_URL=%s\n' "$GLOBAL_PROJECT_PLAN_URL"
printf 'ACCESS_MAP_URL=%s\n' "$ACCESS_MAP_URL"
printf 'XS_MAP_URL=%s\n' "$ACCESS_MAP_URL"
printf 'VM100_PUBLIC_URL=%s\n' "$VM100_PUBLIC_URL"
printf 'VM101_PUBLIC_URL=%s\n' "$VM101_PUBLIC_URL"
printf 'VM121_PUBLIC_URL=%s\n' "$VM121_PUBLIC_URL"
printf 'VM101_MODEL_URL=%s\n' "$VM101_MODEL_URL"
printf 'VM101_METHODS_URL=%s\n' "$VM101_METHODS_URL"
printf 'VM130_SOURCE_URL=%s\n' "$VM130_SOURCE_URL"
printf 'FACTS_URL=%sfacts.json\n' "$STEP_REPORT_URL"
printf 'VERIFY_URL=%sverify.txt\n' "$STEP_REPORT_URL"
printf 'ROLLBACK_URL=%srollback.sh\n' "$STEP_REPORT_URL"
printf 'ARCHITECTURE_PLAN_URL=%s\n' "$ARCHITECTURE_PLAN_URL"
