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

BASE="/home/yeff/public_html/devon"
CANON="$BASE/canon"
DATA="$BASE/panel/data"
DOCS="$BASE/docs/index.php"
HUB="$DATA/hub_index.json"
MASTER="$DATA/master_architecture_index.md"
CONTINUITY="$DATA/devon_continuity.md"

print_file() {
  local f="$1"
  echo
  echo "----- $(basename "$f") -----"
  if [ -f "$f" ]; then
    cat "$f"
  else
    echo "MISSING: $f"
  fi
}

echo "===== CANON ====="
for f in \
  "$CANON/03_RULES_OF_OPERATION.md" \
  "$CANON/06_DECISIONS.md" \
  "$CANON/07_SCOPE.md" \
  "$CANON/08_NEXT_ACTION.md"
do
  print_file "$f"
done

echo
echo "===== CORE ARCHITECTURE ====="
if [ -f "$MASTER" ]; then
  cat "$MASTER"
else
  echo "MISSING: $MASTER"
fi

echo
echo "===== CONTINUITY ====="
if [ -f "$CONTINUITY" ]; then
  cat "$CONTINUITY"
else
  echo "MISSING: $CONTINUITY"
fi

echo



echo
echo "===== DH EXECUTION LAW ====="
cat <<'EOF'
# DOCUMENTATION HUB EXECUTION LAW

Core law:
Documentation Hub is simultaneously:
1. canonical documentation
2. execution system
3. contract base for the future operational panel

DH structural transition law:
Textual validation is transitional only.
The future operational panel must consume structural contract, not textual inference.

Strategic rule:
Documentation Hub is canonical execution guidance, not decorative documentation.
EOF


echo
echo "===== DH JSON MIRROR LAW ====="
cat <<'EOF'
# DOCUMENTATION HUB JSON MIRROR LAW

Core law:
A category that is already structurally mature in Documentation Hub may be materialized as a JSON mirror.

Current meaning:
- DH remains the canonical human-readable reference
- category JSON is the machine-readable mirror of the current DH execution contract
- this JSON is not yet the final sovereign engine contract

Status rule:
When a category JSON is still a DH mirror, its status must communicate transition rather than final sovereignty.
Current valid transition status:
- ACTIVE_DH_MIRROR

Boundary rule:
Do not redesign category macrostructure once the DH category architecture is stable.
After macrostructure is stable, the next step is hardening, not redesign.

Hardening law:
The correct next step after category JSON materialization is:
- strengthen weak evidence
- replace semantic/textual validation where possible
- migrate toward structural evidence, fixed bindings, key paths and schema-backed validation
- do not reopen the category architecture unless there is a real canonical error

Bucket-boundary law:
The following bucket roles must remain rigidly separated:

Validation:
- test conformity against the declared contract

Observable Evidence:
- prove material evidence exists

Completion & Promotion:
- decide whether category status may be promoted

Invalid state:
If these three buckets begin to overlap semantically, the category loses execution clarity and future panel consumption becomes weaker.

Parser-readiness law:
Classification must obey real technical properties, not conservative guessing.

engine_grade_final = true only when:
- evidence is structural
- validation is parseable
- fail state is deterministic
- no human semantic reading is required

parser_readiness = high only when:
- the engine can resolve the check without textual interpretation

validation_mode = semantic_transitional only when:
- the check depends on language interpretation instead of structural keys, bindings or machine-readable contracts

Recalibration rule:
Strong structural checks must not be underclassified merely because the category still contains transitional fields elsewhere.
Item classification must reflect the real strength of that item's own evidence and validation path.

Transition rule:
Current category JSON may be:
- strong for governance
- strong for DH mirroring
- strong for operational contract intent
- partial for parser determinism

This is valid during transition.
It only becomes invalid if DH mirror status is falsely presented as final engine-grade sovereignty.

Strategic direction:
Final architecture target is:
- DH = canonical human-readable execution reference
- category JSON = machine-readable execution mirror
- future operational panel = consumer of hardened structural category contracts
EOF

echo "===== DOCUMENTATION HUB SNAPSHOT ====="
if [ -f "$HUB" ]; then
  python3 - <<'PY'
from pathlib import Path
import json
import re

hub = json.loads(Path("/home/yeff/public_html/devon/panel/data/hub_index.json").read_text())

CATEGORY_PHASE_FALLBACK = {
    "overview_scope": "phase-01",
    "architecture_engineering_core": "phase-02",
    "cognitive_flow": "phase-03",
    "containerization": "phase-04",
    "latency_performance": "phase-05",
    "noise_reduction": "phase-06",
    "observability_audit": "phase-07",
    "security_governance": "phase-08",
    "memory_learning_reasoning": "phase-08",
    "operational_flows": "phase-09",
    "delivery_layer": "phase-09",
    "monitoring_observability": "phase-10",
}

def norm_phase(value):
    if not value:
        return None
    v = str(value).strip().lower().replace("_", "-")
    m = re.match(r"phase[- ]?(\d+)$", v)
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return v

def parse_phase_from_badge(badge):
    if not badge:
        return None
    m = re.search(r"phase[- ]?(\d+)", str(badge).lower())
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return None

def phase_id_of(ph, idx):
    return norm_phase(
        ph.get("id")
        or ph.get("phase_id")
        or ph.get("key")
        or f"phase-{idx+1:02d}"
    )

def phase_label_of(ph, idx):
    return (
        ph.get("label")
        or ph.get("title")
        or ph.get("name")
        or ph.get("badge")
        or phase_id_of(ph, idx)
    )

def category_label(cat):
    return cat.get("label") or cat.get("title") or cat.get("name") or cat.get("id")

def doc_label(doc):
    return doc.get("label") or doc.get("title") or doc.get("name") or doc.get("id")

def category_phase(cat):
    explicit = (
        cat.get("phase_id")
        or cat.get("phase")
        or cat.get("phase_ref")
        or cat.get("parent_phase")
    )
    explicit = norm_phase(explicit)
    if explicit:
        return explicit

    docs = cat.get("docs", [])
    if docs:
        doc_phase = norm_phase(docs[0].get("phase"))
        if doc_phase:
            return doc_phase

    badge_phase = parse_phase_from_badge(cat.get("badge"))
    if badge_phase:
        return badge_phase

    return CATEGORY_PHASE_FALLBACK.get(cat.get("id"), "UNBOUND")

phases = hub.get("phases", [])
cats = hub.get("categories", [])

print("PHASE COUNT:", len(phases))
for i, ph in enumerate(phases):
    print(f"- {phase_id_of(ph, i)} | {phase_label_of(ph, i)}")

print()
print("CATEGORY COUNT:", len(cats))
for cat in cats:
    docs = cat.get("docs", [])
    print(f"CATEGORY: {cat.get('id')} | LABEL: {category_label(cat)} | PHASE: {category_phase(cat)} | DOCS: {len(docs)}")
    for doc in docs:
        print(f"  DOC: {doc.get('id')} | LABEL: {doc_label(doc)} | TYPE: {doc.get('type')}")
    print()
PY
else
  echo "MISSING: $HUB"
fi

echo
echo "===== PHASE 01 + PHASE 02 DOC MAP ====="
if [ -f "$HUB" ]; then
  python3 - <<'PY'
from pathlib import Path
import json
import re

hub = json.loads(Path("/home/yeff/public_html/devon/panel/data/hub_index.json").read_text())

CATEGORY_PHASE_FALLBACK = {
    "overview_scope": "phase-01",
    "architecture_engineering_core": "phase-02",
    "cognitive_flow": "phase-03",
    "containerization": "phase-04",
    "latency_performance": "phase-05",
    "noise_reduction": "phase-06",
    "observability_audit": "phase-07",
    "security_governance": "phase-08",
    "memory_learning_reasoning": "phase-08",
    "operational_flows": "phase-09",
    "delivery_layer": "phase-09",
    "monitoring_observability": "phase-10",
}

def norm_phase(value):
    if not value:
        return None
    v = str(value).strip().lower().replace("_", "-")
    m = re.match(r"phase[- ]?(\d+)$", v)
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return v

def parse_phase_from_badge(badge):
    if not badge:
        return None
    m = re.search(r"phase[- ]?(\d+)", str(badge).lower())
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return None

def category_label(cat):
    return cat.get("label") or cat.get("title") or cat.get("name") or cat.get("id")

def doc_label(doc):
    return doc.get("label") or doc.get("title") or doc.get("name") or doc.get("id")

def category_phase(cat):
    explicit = (
        cat.get("phase_id")
        or cat.get("phase")
        or cat.get("phase_ref")
        or cat.get("parent_phase")
    )
    explicit = norm_phase(explicit)
    if explicit:
        return explicit

    docs = cat.get("docs", [])
    if docs:
        doc_phase = norm_phase(docs[0].get("phase"))
        if doc_phase:
            return doc_phase

    badge_phase = parse_phase_from_badge(cat.get("badge"))
    if badge_phase:
        return badge_phase

    return CATEGORY_PHASE_FALLBACK.get(cat.get("id"), "UNBOUND")

for phase in ("phase-01", "phase-02"):
    print(f"[{phase}]")
    found = False
    for cat in hub.get("categories", []):
        if category_phase(cat) != phase:
            continue
        found = True
        print(f"  {cat.get('id')} => {category_label(cat)}")
        for doc in cat.get("docs", []):
            print(f"    - {doc.get('id')} => {doc_label(doc)}")
    if not found:
        print("  MISSING")
    print()
PY
else
  echo "MISSING: $HUB"
fi

echo
echo "===== DOCS INDEX CUSTOM BRANCHES ====="
if [ -f "$DOCS" ]; then
  grep -n 'if (doc.id === "' "$DOCS" || true
else
  echo "MISSING: $DOCS"
fi

echo
echo "===== DOCS INDEX forceDirectArchitectureRender ====="
if [ -f "$DOCS" ]; then
  python3 - <<'PY'
from pathlib import Path

s = Path("/home/yeff/public_html/devon/docs/index.php").read_text()
needle = "const forceDirectArchitectureRender ="
i = s.find(needle)
if i == -1:
    print("MISSING: forceDirectArchitectureRender block")
else:
    j = s.find("if (!forceDirectArchitectureRender)", i)
    if j == -1:
        j = min(len(s), i + 2200)
    print(s[i:j].rstrip())
PY
else
  echo "MISSING: $DOCS"
fi

echo
echo "===== DOCS INDEX PHASE STATUS SNAPSHOT ====="
if [ -f "$DOCS" ] && [ -f "$HUB" ]; then
  python3 - <<'PY'
from pathlib import Path
import json
import re

docs_text = Path("/home/yeff/public_html/devon/docs/index.php").read_text()
hub = json.loads(Path("/home/yeff/public_html/devon/panel/data/hub_index.json").read_text())

CATEGORY_PHASE_FALLBACK = {
    "overview_scope": "phase-01",
    "architecture_engineering_core": "phase-02",
    "cognitive_flow": "phase-03",
    "containerization": "phase-04",
    "latency_performance": "phase-05",
    "noise_reduction": "phase-06",
    "observability_audit": "phase-07",
    "security_governance": "phase-08",
    "memory_learning_reasoning": "phase-08",
    "operational_flows": "phase-09",
    "delivery_layer": "phase-09",
    "monitoring_observability": "phase-10",
}

def norm_phase(value):
    if not value:
        return None
    v = str(value).strip().lower().replace("_", "-")
    m = re.match(r"phase[- ]?(\d+)$", v)
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return v

def parse_phase_from_badge(badge):
    if not badge:
        return None
    m = re.search(r"phase[- ]?(\d+)", str(badge).lower())
    if m:
        return f"phase-{int(m.group(1)):02d}"
    return None

def category_label(cat):
    return cat.get("label") or cat.get("title") or cat.get("name") or cat.get("id")

def category_phase(cat):
    explicit = (
        cat.get("phase_id")
        or cat.get("phase")
        or cat.get("phase_ref")
        or cat.get("parent_phase")
    )
    explicit = norm_phase(explicit)
    if explicit:
        return explicit

    docs = cat.get("docs", [])
    if docs:
        doc_phase = norm_phase(docs[0].get("phase"))
        if doc_phase:
            return doc_phase

    badge_phase = parse_phase_from_badge(cat.get("badge"))
    if badge_phase:
        return badge_phase

    return CATEGORY_PHASE_FALLBACK.get(cat.get("id"), "UNBOUND")

branches = set()
for m in re.finditer(r'if \(doc\.id === "([^"]+)" && state\.categoryId === "([^"]+)"\)', docs_text):
    branches.add((m.group(1), m.group(2)))

for phase in ("phase-01", "phase-02"):
    print(f"{phase.upper()}:")
    found = False
    for cat in hub.get("categories", []):
        if category_phase(cat) != phase:
            continue
        found = True
        cat_id = cat.get("id")
        print(f"  CATEGORY: {cat_id} | {category_label(cat)}")
        for doc in cat.get("docs", []):
            doc_id = doc.get("id")
            status = "CUSTOM_BRANCH" if (doc_id, cat_id) in branches else "GENERIC_RENDER"
            print(f"    - {doc_id}: {status}")
    if not found:
        print("  MISSING")
    print()
PY
else
  echo "MISSING: $DOCS or $HUB"
fi

echo
echo "===== DOCS INDEX SYNTAX ====="
if [ -f "$DOCS" ]; then
  php -l "$DOCS" || true
else
  echo "MISSING: $DOCS"
fi

echo
echo "===== DUMP STATUS ====="
echo "PASS: canonical + docs + hub context reconstructed from server evidence"
