#!/usr/bin/env python3
"""Real-time background graph-builder for dual-perspective living archives.

Zero-external-dependency Python 3 engine + CLI. Ingests a stream of spoken
transcript turns (JSONL) alongside sparse archive metadata (JSON), resolves
time-scoped places, relational roles, and years, attaches audio timestamp spans
(t0..t1) to nodes, preserves Perspective A (Child) and Perspective B (Parent)
separately on shared coordinates, detects perspective divergences and EXIF
clashes, and ranks remaining archive gaps by risk-adjusted Expected Information
Gain (EIG / C_trust).
"""

from __future__ import annotations

import argparse
import json
import math
import re
import sys
from pathlib import Path
from typing import Any

# Provenance hierarchy (Tier 1 outranks retrospective spoken recall for dates/coords)
PROVENANCE_TIERS = {
    1: "tier1_hardware_exif",
    2: "tier2_contemporaneous_scan",
    3: "tier3_spoken_recall",
    4: "tier4_inferred_link",
}

YEAR_RE = re.compile(r"\b(19[5-9]\d|20[0-2]\d)\b")

PEOPLE_PATTERNS = {
    "classmate": re.compile(r"\bclassmates?\b", re.I),
    "teacher": re.compile(r"\bteachers?\b", re.I),
    "neighbour": re.compile(r"\bneighbou?rs?\b", re.I),
    "relatives": re.compile(r"\b(?:relatives?|grandparents?|aunt|uncle|cousins?)\b", re.I),
    "friend": re.compile(r"\bfriends?\b", re.I),
    "landlord": re.compile(r"\blandlord\b", re.I),
    "colleague": re.compile(r"\bcolleagues?\b", re.I),
}

DETAIL_LEXICON = [
    ("watermelon", ["watermelon"]),
    ("cicadas", ["cicadas", "cicada"]),
    ("bicycle", ["bicycle", "bike"]),
    ("suitcases", ["suitcases", "suitcase", "luggage"]),
    ("exit paperwork", ["paperwork", "exit paperwork", "forms", "translating forms"]),
    ("winter flight", ["winter flight", "flight"]),
    ("green hills", ["green hills", "hills"]),
    ("duck pond & geese", ["duck pond", "geese", "pond"]),
    ("conkers", ["conkers"]),
    ("damp rented room", ["damp rented room", "rented room", "damp"]),
    ("winter mud & bus walk", ["winter mud", "bus walk", "mud"]),
    ("corner park walk", ["corner park", "through the park", "walked through the park"]),
    ("tuesday park walk", ["tuesday", "every tuesday"]),
    ("weekday school routine", ["every weekday", "every afternoon", "after primary school"]),
    ("bus hub", ["bus hub", "primary school"]),
    ("housing queues", ["housing office", "temporary tenancies", "precarious"]),
    ("night bus shifts", ["night bus", "shifts", "rent covered"]),
    ("painted walls", ["painted the walls", "painted walls"]),
    ("quiet corner desk", ["corner desk", "exams"]),
    ("permanent lease", ["lease", "permanent", "real home"]),
    ("hallway carpet", ["hallway carpet", "carpet"]),
    ("first desk job", ["desk job", "fresh start"]),
    ("river ferry & boxes", ["river ferry", "ferry", "boxes", "blossom quay"]),
    ("lockdown easing", ["lockdown"]),
    ("interim hill steps", ["interim", "interim hill", "estate steps", "brick steps", "snow"]),
]

POSITIVE_LEXICON = {
    "warm": 0.35,
    "summer": 0.20,
    "singing": 0.25,
    "watermelon": 0.25,
    "endless": 0.25,
    "green": 0.20,
    "chasing": 0.25,
    "conkers": 0.20,
    "solid": 0.25,
    "routine": 0.15,
    "walked": 0.15,
    "walking": 0.15,
    "quiet": 0.20,
    "calm": 0.35,
    "proud": 0.45,
    "relief": 0.45,
    "settled": 0.35,
    "real home": 0.30,
    "fresh start": 0.40,
    "blossom": 0.25,
    "together": 0.25,
    "park": 0.15,
}

NEGATIVE_LEXICON = {
    "exhausting": -0.45,
    "midnight": -0.15,
    "queuing": -0.25,
    "queues": -0.25,
    "worrying": -0.35,
    "stranded": -0.40,
    "damp": -0.35,
    "mud": -0.25,
    "lonely": -0.45,
    "translating forms": -0.25,
    "precarious": -0.40,
    "temporary": -0.20,
    "crowded": -0.25,
    "night bus shifts": -0.30,
    "stress": -0.40,
    "cold": -0.10,
    "lockdown": -0.15,
}

STOPWORDS = {
    "about", "after", "again", "always", "around", "before", "between", "could",
    "every", "felt", "finally", "from", "into", "just", "later", "like", "looking",
    "mostly", "moving", "near", "onto", "ourselves", "past", "really", "remember",
    "right", "that", "their", "there", "these", "this", "through", "together",
    "until", "very", "wait", "watching", "when", "where", "whether", "with",
    "would", "years", "actually",
}


def extract_years(text: str) -> list[int]:
    return sorted({int(y) for y in YEAR_RE.findall(text)})


def extract_people(text: str) -> list[str]:
    found = [role for role, pat in PEOPLE_PATTERNS.items() if pat.search(text)]
    return sorted(found)


def extract_details(text: str) -> list[str]:
    lower = text.lower()
    motifs: list[str] = []
    for label, phrases in DETAIL_LEXICON:
        if any(phrase in lower for phrase in phrases):
            motifs.append(label)
    if not motifs:
        # Fallback for custom user turns: pull distinctive content words
        tokens = re.findall(r"[a-z]{5,}", lower)
        for tok in tokens:
            if tok not in STOPWORDS and tok not in motifs:
                motifs.append(tok)
            if len(motifs) >= 3:
                break
    return motifs


def score_salience(text: str) -> tuple[str, float]:
    lower = text.lower()
    raw = 0.0
    hits = 0
    for phrase, weight in POSITIVE_LEXICON.items():
        if phrase in lower:
            raw += weight
            hits += 1
    for phrase, weight in NEGATIVE_LEXICON.items():
        if phrase in lower:
            raw += weight
            hits += 1
    # Smooth tanh squash prevents saturation at +/-1.0 and preserves relative spread
    valence = round(math.tanh(raw * 0.85), 2)
    if hits == 0 or abs(valence) < 0.12:
        return "neutral_recall", valence
    if valence > 0:
        if any(w in lower for w in ("relief", "settled", "calm", "lease", "painted", "carpet")):
            return "settled_pride", valence
        if any(w in lower for w in ("fresh start", "desk job", "blossom", "ferry", "proud")):
            return "fresh_start", valence
        if any(w in lower for w in ("routine", "walked", "walking", "bus hub", "primary school", "tuesday")):
            return "routine_belonging", valence
        return "warm_wonder", valence
    if any(w in lower for w in ("lonely", "damp", "mud")):
        return "isolation_stress", valence
    if any(w in lower for w in ("precarious", "temporary", "housing", "keep rent", "night bus")):
        return "precarious_effort", valence
    return "logistical_strain", valence


def shannon_entropy(probs: list[float]) -> float:
    total = sum(p for p in probs if p > 0)
    if total <= 0:
        return 0.0
    h = 0.0
    for p in probs:
        if p > 0:
            q = p / total
            h -= q * math.log2(q)
    return h


class DualMemoryGraphBuilder:
    """Streaming dual-perspective memory graph builder with provenance & EIG."""

    def __init__(self, artifacts_payload: dict[str, Any]) -> None:
        self.dataset_id: str = artifacts_payload.get("dataset_id", "custom")
        self.places: dict[str, dict[str, Any]] = {}
        self.artifacts: dict[str, dict[str, Any]] = {}
        self.gaps: dict[str, dict[str, Any]] = {}
        self.edges: list[dict[str, Any]] = []
        self.turns: list[dict[str, Any]] = []
        self.people_nodes: dict[str, dict[str, Any]] = {}

        for p in artifacts_payload.get("places", []):
            pid = p["id"]
            self.places[pid] = {
                "id": pid,
                "label": p["label"],
                "region": p["region"],
                "era": list(p["era"]),
                "coords": dict(p["coords"]),
                "aliases": list(p.get("aliases", [])),
                "provisional": bool(p.get("provisional", False)),
                "exif_anchors": [],
                "linked_artifacts": [],
                "perspectives": {
                    "child": self._empty_perspective(),
                    "parent": self._empty_perspective(),
                },
                "divergence": None,
                "agreement": None,
            }

        for art in artifacts_payload.get("artifacts", []):
            aid = art["id"]
            item = dict(art)
            item["linked_turn_ids"] = []
            self.artifacts[aid] = item
            if item.get("provenance_tier") == 1 and item.get("place_hint") in self.places:
                pid = item["place_hint"]
                exif_year = int(item["exif_date"][:4]) if item.get("exif_date") else None
                self.places[pid]["exif_anchors"].append({
                    "artifact_id": aid,
                    "filename": item["filename"],
                    "exif_date": item["exif_date"],
                    "exif_year": exif_year,
                    "gps_region": item.get("gps_region"),
                })
                if aid not in self.places[pid]["linked_artifacts"]:
                    self.places[pid]["linked_artifacts"].append(aid)
                self._add_edge(
                    source=aid,
                    target=pid,
                    edge_type="exif_anchors_place",
                    provenance_tier=1,
                    perspective="hardware",
                    audio_span=None,
                    note=f"EXIF {item['exif_date']} ({item.get('gps_region')})",
                )

        for g in artifacts_payload.get("initial_gaps", []):
            gid = g["id"]
            gap_copy = json.loads(json.dumps(g))
            gap_copy["resolved"] = False
            gap_copy["resolved_by_turns"] = []
            self.gaps[gid] = gap_copy

    @staticmethod
    def _empty_perspective() -> dict[str, Any]:
        return {
            "turn_ids": [],
            "audio_spans": [],
            "years_claimed": [],
            "details": [],
            "people": [],
            "salience_tags": [],
            "valence_scores": [],
            "mean_valence": None,
            "dominant_salience": None,
            "snippets": [],
        }

    def _add_edge(
        self,
        source: str,
        target: str,
        edge_type: str,
        provenance_tier: int,
        perspective: str,
        audio_span: list[float] | None,
        note: str,
    ) -> dict[str, Any]:
        edge_id = f"e{len(self.edges) + 1:03d}"
        edge = {
            "id": edge_id,
            "source": source,
            "target": target,
            "edge_type": edge_type,
            "provenance_tier": provenance_tier,
            "provenance_label": PROVENANCE_TIERS.get(provenance_tier, "unknown"),
            "perspective": perspective,
            "audio_span": audio_span,
            "note": note,
        }
        self.edges.append(edge)
        return edge

    def _resolve_place(self, text: str, years: list[int]) -> tuple[str, str]:
        """Time-scoped place resolution preventing flat-name era collapse."""
        lower = text.lower()
        scores: list[tuple[float, str, str]] = []

        # Check if turn directly bridges an unresolved temporal void (e.g., 2008-2010)
        for gid, gap in self.gaps.items():
            if gap["resolved"]:
                continue
            y0, y1 = gap["year_span"]
            year_in_gap = any(y0 <= y <= y1 for y in years)
            gap_kw_hit = any(
                kw in lower for kw in ("interim", "bridge", "2008", "2009", "2010", "estate steps", "snow", "hill")
            )
            if year_in_gap and gap_kw_hit and gid == "gap_2008_2010_bridge":
                pid = "interim_north_london_2008"
                if pid not in self.places:
                    self.places[pid] = {
                        "id": pid,
                        "label": "Interim North London flat (provisional)",
                        "region": gap["region"],
                        "era": list(gap["year_span"]),
                        "coords": dict(gap["coords"]),
                        "aliases": ["interim", "hill", "estate steps", "2008", "2009"],
                        "provisional": True,
                        "exif_anchors": [],
                        "linked_artifacts": [],
                        "perspectives": {
                            "child": self._empty_perspective(),
                            "parent": self._empty_perspective(),
                        },
                        "divergence": None,
                        "agreement": None,
                    }
                return pid, "materialized_gap_node"

        for pid, place in self.places.items():
            score = 0.0
            reason_parts: list[str] = []
            # 1. Exact alias & region matching (longer aliases carry higher specificity)
            for alias in place["aliases"]:
                if alias in lower:
                    specificity = 3.0 if len(alias.split()) >= 2 else 1.8
                    # Shared region token ("north london") gets smaller weight so era decides
                    if alias == "north london":
                        specificity = 1.4
                    score += specificity
                    reason_parts.append(f"alias:{alias}")

            # 2. Time-scoped era disambiguation
            era_start, era_end = place["era"]
            if years:
                min_dist = min(
                    0 if era_start <= y <= era_end else min(abs(y - era_start), abs(y - era_end))
                    for y in years
                )
                if min_dist == 0:
                    score += 3.5
                    reason_parts.append("era_exact")
                elif min_dist == 1:
                    score += 1.6
                    reason_parts.append("era_adjacent")
                elif min_dist <= 3:
                    score += 0.3
                else:
                    # Penalize distant eras so "North London 2012" never collapses into 2004
                    score -= min(3.0, min_dist * 0.45)

            if score > 0:
                scores.append((score, pid, "+".join(reason_parts) or "heuristic"))

        if scores:
            scores.sort(key=lambda item: item[0], reverse=True)
            return scores[0][1], scores[0][2]

        # Fallback: attach by nearest year if available, else create a provisional note node
        if years:
            y_ref = years[0]
            best_pid = min(
                self.places.keys(),
                key=lambda pid: min(abs(y_ref - self.places[pid]["era"][0]), abs(y_ref - self.places[pid]["era"][1])),
            )
            return best_pid, "nearest_era_fallback"

        return "north_london_early_2004", "default_context_fallback"

    def _anchor_matching_artifacts(
        self, place_id: str, text: str, years: list[int], turn_id: str, speaker: str, span: list[float]
    ) -> list[str]:
        lower = text.lower()
        newly_anchored: list[str] = []
        place = self.places[place_id]
        for aid, art in self.artifacts.items():
            if art["status"] == "exif_anchored":
                continue
            hint = art.get("place_hint")
            # Match either by place_hint + keyword/year overlap, or orphan within active year span
            kw_hits = sum(1 for kw in art.get("keywords", []) if kw.lower() in lower)
            yr0, yr1 = art.get("approx_year_range", [0, 0])
            year_hit = any(yr0 <= y <= yr1 for y in years)
            if hint == place_id and (kw_hits >= 1 or (year_hit and art["status"] == "orphan" and kw_hits >= 1)):
                matched = True
            elif hint is None and place.get("provisional") and (kw_hits >= 1 or year_hit):
                matched = True
            else:
                matched = False

            if matched:
                if art["status"] == "orphan":
                    art["status"] = "voice_anchored"
                    art["anchored_place_id"] = place_id
                    newly_anchored.append(aid)
                    if aid not in place["linked_artifacts"]:
                        place["linked_artifacts"].append(aid)
                    self._add_edge(
                        source=aid,
                        target=place_id,
                        edge_type="voice_anchors_artifact",
                        provenance_tier=3,
                        perspective=speaker,
                        audio_span=span,
                        note=f"{turn_id} linked {art['filename']} via spoken cues",
                    )
                if turn_id not in art["linked_turn_ids"]:
                    art["linked_turn_ids"].append(turn_id)
        return newly_anchored

    def _update_gaps_from_turn(self, place_id: str, text: str, years: list[int], turn_id: str) -> list[str]:
        lower = text.lower()
        touched_gaps: list[str] = []
        for gid, gap in self.gaps.items():
            if gap["resolved"]:
                continue
            y0, y1 = gap["year_span"]
            year_hit = any(y0 <= y <= y1 for y in years)
            # Check if any orphan artifacts in this gap were just anchored
            remaining_orphans = [
                aid for aid in gap["orphan_artifacts"] if self.artifacts.get(aid, {}).get("status") == "orphan"
            ]
            gap["orphan_artifacts"] = remaining_orphans

            # Gap 1: 2008-2010 interim bridge addressed directly
            if gid == "gap_2008_2010_bridge" and (place_id == "interim_north_london_2008" or (year_hit and any(k in lower for k in ("interim", "steps", "hill", "snow", "commute")))):
                gap["candidate_hypotheses"] = [
                    {"target": "interim_north_london_2008", "prob": 0.92},
                    {"target": "north_london_early_2004", "prob": 0.04},
                    {"target": "north_london_later_2011", "prob": 0.04},
                ]
                gap["unlinked_boundaries"] = max(0, gap["unlinked_boundaries"] - 1)
                gap["resolved_by_turns"].append(turn_id)
                if not remaining_orphans:
                    gap["resolved"] = True
                touched_gaps.append(gid)
            # Gap 2: 2003 village assembly addressed
            elif gid == "gap_2003_village_school" and (year_hit and any(k in lower for k in ("assembly", "school", "autumn"))):
                gap["candidate_hypotheses"] = [
                    {"target": "sussex_village_2002", "prob": 0.96},
                    {"target": "north_london_early_2004", "prob": 0.04},
                ]
                gap["resolved"] = True
                gap["resolved_by_turns"].append(turn_id)
                touched_gaps.append(gid)
            # Gap 3: Beijing departure slip anchored
            elif gid == "gap_2001_departure_week" and year_hit and any(k in lower for k in ("suitcase", "flight", "departure", "paperwork")):
                # Narrow posterior partially (parent mentioned departure logistics, but departure week slip still needs confirmation)
                gap["candidate_hypotheses"] = [
                    {"target": "beijing_courtyard_2000", "prob": 0.78},
                    {"target": "sussex_village_2002", "prob": 0.22},
                ]
                gap["resolved_by_turns"].append(turn_id)
                touched_gaps.append(gid)
        return touched_gaps

    def _evaluate_perspectives(self, place_id: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
        """Detect divergence (salience, detail, or temporal/EXIF clash) vs. agreement."""
        place = self.places[place_id]
        child = place["perspectives"]["child"]
        parent = place["perspectives"]["parent"]
        exif_years = sorted({a["exif_year"] for a in place["exif_anchors"] if a.get("exif_year")})

        has_child = bool(child["turn_ids"])
        has_parent = bool(parent["turn_ids"])
        era_start, era_end = place["era"]
        if not (has_child and has_parent):
            # Still check single-speaker EXIF temporal clash (claimed year outside EXIF-corroborated era)
            if exif_years:
                for spk, rec in (("child", child), ("parent", parent)):
                    bad_years = sorted(y for y in rec["years_claimed"] if y < era_start or y > era_end)
                    if bad_years:
                        div = {
                            "place_id": place_id,
                            "place_label": place["label"],
                            "kind": "temporal_clash",
                            "severity": "high",
                            "canonical_year": exif_years[0],
                            "child_years": child["years_claimed"],
                            "parent_years": parent["years_claimed"],
                            "valence_delta": 0.0,
                            "summary": f"{spk.title()} recalled {bad_years} while Tier 1 EXIF anchors {exif_years[0]} ({era_start}–{era_end}); spoken claim preserved as superseded.",
                            "superseded_claim": {"speaker": spk, "years": bad_years},
                        }
                        place["divergence"] = div
                        place["agreement"] = None
                        return div, None
            return None, None

        # Both Perspective A (Child) and Perspective B (Parent) present on shared coordinate
        c_val = child["mean_valence"] if child["mean_valence"] is not None else 0.0
        p_val = parent["mean_valence"] if parent["mean_valence"] is not None else 0.0
        v_delta = round(abs(c_val - p_val), 2)

        c_details = set(child["details"])
        p_details = set(parent["details"])
        union_len = len(c_details | p_details) or 1
        detail_jaccard = round(len(c_details & p_details) / union_len, 2)

        # 1. Check temporal / EXIF clash first
        # A mid-era photo (e.g. 2014 inside 2011–2016) does NOT contradict a 2012 move-in memory;
        # a clash fires when a claimed year falls outside the EXIF-corroborated era span.
        c_years = set(child["years_claimed"])
        p_years = set(parent["years_claimed"])
        exif_clash = False
        superseded = None
        if exif_years:
            for spk, yset in (("child", c_years), ("parent", p_years)):
                bad_years = sorted(y for y in yset if y < era_start or y > era_end)
                if bad_years:
                    exif_clash = True
                    superseded = {"speaker": spk, "years": bad_years}
        speaker_year_gap = bool(c_years and p_years and min(abs(a - b) for a in c_years for b in p_years) >= 1 and not (c_years & p_years))
        outside_era = any(y < era_start or y > era_end for y in (c_years | p_years))

        if exif_clash or (speaker_year_gap and outside_era):
            canonical_yr = exif_years[0] if exif_years else (sorted(p_years)[0] if p_years else era_start)
            div = {
                "place_id": place_id,
                "place_label": place["label"],
                "kind": "temporal_clash",
                "severity": "high",
                "canonical_year": canonical_yr,
                "child_years": sorted(c_years),
                "parent_years": sorted(p_years),
                "child_salience": child["dominant_salience"],
                "parent_salience": parent["dominant_salience"],
                "valence_delta": v_delta,
                "detail_overlap": detail_jaccard,
                "superseded_claim": superseded,
                "summary": (
                    f"Child recalled {sorted(c_years)} vs. Parent {sorted(p_years)}"
                    + (f" and Tier 1 EXIF {canonical_yr}; EXIF locks canonical timeline while Child claim stays intact." if exif_years else ".")
                ),
            }
            place["divergence"] = div
            place["agreement"] = None
            return div, None

        # 2. Check emotional salience split
        if v_delta >= 0.75:
            severity = "high" if v_delta >= 1.15 else "medium"
            div = {
                "place_id": place_id,
                "place_label": place["label"],
                "kind": "salience_split",
                "severity": severity,
                "canonical_year": exif_years[0] if exif_years else era_start,
                "child_years": sorted(c_years),
                "parent_years": sorted(p_years),
                "child_salience": child["dominant_salience"],
                "parent_salience": parent["dominant_salience"],
                "valence_delta": v_delta,
                "detail_overlap": detail_jaccard,
                "superseded_claim": None,
                "summary": (
                    f"Same coordinate ({place['label']}), opposing lived valence (Δ={v_delta:.2f}): "
                    f"Child highlights {', '.join(child['details'][:2]) or child['dominant_salience']} ({c_val:+.2f}); "
                    f"Parent highlights {', '.join(parent['details'][:2]) or parent['dominant_salience']} ({p_val:+.2f})."
                ),
            }
            place["divergence"] = div
            place["agreement"] = None
            return div, None

        # 3. Check detail divergence with moderate emotional spread
        if detail_jaccard < 0.20 and v_delta >= 0.45:
            div = {
                "place_id": place_id,
                "place_label": place["label"],
                "kind": "detail_divergence",
                "severity": "medium",
                "canonical_year": exif_years[0] if exif_years else era_start,
                "child_years": sorted(c_years),
                "parent_years": sorted(p_years),
                "child_salience": child["dominant_salience"],
                "parent_salience": parent["dominant_salience"],
                "valence_delta": v_delta,
                "detail_overlap": detail_jaccard,
                "superseded_claim": None,
                "summary": f"Distinct recalled details (overlap={detail_jaccard:.2f}) and valence spread Δ={v_delta:.2f} at {place['label']}.",
            }
            place["divergence"] = div
            place["agreement"] = None
            return div, None

        # 4. Convergent anchor (both speakers align on era and emotional tone)
        agree = {
            "place_id": place_id,
            "place_label": place["label"],
            "kind": "convergent_anchor",
            "child_salience": child["dominant_salience"],
            "parent_salience": parent["dominant_salience"],
            "valence_delta": v_delta,
            "summary": (
                f"Both perspectives align at {place['label']} (Δvalence={v_delta:.2f}): "
                f"Child ({child['dominant_salience']}) and Parent ({parent['dominant_salience']}) reinforce the same milestone."
            ),
        }
        place["divergence"] = None
        place["agreement"] = agree
        return None, agree

    def compute_eig_gaps(self) -> list[dict[str, Any]]:
        """Rank unresolved archive gaps by risk-adjusted EIG / C_trust."""
        r_turn = 0.78       # expected single-turn uncertainty reduction rate
        h_art = 0.35        # bits gained per disambiguated orphan artifact
        h_bridge = 0.40     # bits gained per bridged era boundary
        ranked: list[dict[str, Any]] = []

        for gid, gap in self.gaps.items():
            probs = [float(c["prob"]) for c in gap["candidate_hypotheses"]]
            entropy_bits = round(shannon_entropy(probs), 3)
            m_orphans = len(gap["orphan_artifacts"])
            b_bounds = int(gap["unlinked_boundaries"])
            eig_bits = 0.0 if gap["resolved"] else round(r_turn * entropy_bits + m_orphans * h_art + b_bounds * h_bridge, 3)
            c_trust = round(1.0 + 1.2 * float(gap["sensitivity"]) + 0.8 * (1.0 - float(gap["reversibility"])), 3)
            priority = round(eig_bits / c_trust, 3) if c_trust > 0 else 0.0

            ranked.append({
                "id": gid,
                "label": gap["label"],
                "region": gap["region"],
                "year_span": gap["year_span"],
                "coords": gap["coords"],
                "resolved": gap["resolved"],
                "entropy_bits": entropy_bits,
                "orphan_count": m_orphans,
                "orphan_artifacts": list(gap["orphan_artifacts"]),
                "unlinked_boundaries": b_bounds,
                "eig_bits": eig_bits,
                "sensitivity": gap["sensitivity"],
                "reversibility": gap["reversibility"],
                "trust_cost": c_trust,
                "priority_score": priority,
                "prompt_cue": gap["prompt_cue"],
            })

        ranked.sort(key=lambda item: (item["resolved"], -item["priority_score"]))
        return ranked

    def ingest_turn(self, event: dict[str, Any]) -> dict[str, Any]:
        """Process one streaming transcript turn and return its graph delta."""
        turn_id = event.get("turn_id") or f"t{len(self.turns) + 1:02d}"
        speaker = str(event["speaker"]).strip().lower()
        if speaker not in ("child", "parent"):
            raise ValueError(f"Unsupported speaker perspective: {speaker!r} (expected 'child' or 'parent')")
        t0 = float(event["t0"])
        t1 = float(event["t1"])
        if t1 < t0:
            raise ValueError(f"Invalid audio span [{t0}, {t1}] on turn {turn_id}")
        text = str(event["text"]).strip()
        span = [round(t0, 2), round(t1, 2)]

        years = extract_years(text)
        people = extract_people(text)
        details = extract_details(text)
        salience_tag, valence = score_salience(text)
        place_id, resolution_reason = self._resolve_place(text, years)

        place = self.places[place_id]
        persp = place["perspectives"][speaker]
        persp["turn_ids"].append(turn_id)
        persp["audio_spans"].append(span)
        for y in years:
            if y not in persp["years_claimed"]:
                persp["years_claimed"].append(y)
        persp["years_claimed"].sort()
        for d in details:
            if d not in persp["details"]:
                persp["details"].append(d)
        for role in people:
            if role not in persp["people"]:
                persp["people"].append(role)
            pnode = self.people_nodes.setdefault(role, {"id": f"person_{role}", "role": role, "places": [], "turn_ids": []})
            if place_id not in pnode["places"]:
                pnode["places"].append(place_id)
            pnode["turn_ids"].append(turn_id)
            self._add_edge(
                source=f"person_{role}",
                target=place_id,
                edge_type="role_present_at",
                provenance_tier=3,
                perspective=speaker,
                audio_span=span,
                note=f"{speaker} mentioned {role} in {turn_id}",
            )

        persp["salience_tags"].append(salience_tag)
        persp["valence_scores"].append(valence)
        persp["mean_valence"] = round(sum(persp["valence_scores"]) / len(persp["valence_scores"]), 2)
        persp["dominant_salience"] = max(set(persp["salience_tags"]), key=persp["salience_tags"].count)
        persp["snippets"].append({"turn_id": turn_id, "span": span, "text": text})

        new_edges: list[dict[str, Any]] = []
        edge = self._add_edge(
            source=f"perspective_{speaker}",
            target=place_id,
            edge_type=f"{speaker}_recounts_place",
            provenance_tier=3,
            perspective=speaker,
            audio_span=span,
            note=f"{salience_tag} ({valence:+.2f}); motifs: {', '.join(details[:3])}",
        )
        new_edges.append(edge)

        # Wire chronological transition edge if speaker previously anchored an earlier place
        prev_turns = [t for t in self.turns if t["speaker"] == speaker and t["resolved_place_id"] != place_id]
        if prev_turns:
            prev_place_id = prev_turns[-1]["resolved_place_id"]
            already = any(
                e["source"] == prev_place_id and e["target"] == place_id and e["perspective"] == speaker and e["edge_type"] == "chronological_move"
                for e in self.edges
            )
            if not already:
                trans_edge = self._add_edge(
                    source=prev_place_id,
                    target=place_id,
                    edge_type="chronological_move",
                    provenance_tier=3,
                    perspective=speaker,
                    audio_span=span,
                    note=f"{speaker} narrative sequence",
                )
                new_edges.append(trans_edge)

        anchored_artifacts = self._anchor_matching_artifacts(place_id, text, years, turn_id, speaker, span)
        touched_gaps = self._update_gaps_from_turn(place_id, text, years, turn_id)
        divergence, agreement = self._evaluate_perspectives(place_id)
        if divergence:
            # Record explicit divergence edge between the two perspective layers on this place
            already_div = any(e["target"] == place_id and e["edge_type"] == "perspective_divergence" for e in self.edges)
            if not already_div:
                new_edges.append(
                    self._add_edge(
                        source="perspective_child",
                        target=place_id,
                        edge_type="perspective_divergence",
                        provenance_tier=4,
                        perspective="overlay",
                        audio_span=span,
                        note=f"{divergence['kind']}: Δvalence={divergence['valence_delta']:.2f}",
                    )
                )

        delta = {
            "turn_id": turn_id,
            "speaker": speaker,
            "audio_span": span,
            "text": text,
            "resolved_place_id": place_id,
            "resolved_place_label": place["label"],
            "resolution_reason": resolution_reason,
            "extracted_years": years,
            "extracted_people": people,
            "extracted_details": details,
            "salience": salience_tag,
            "valence": valence,
            "newly_anchored_artifacts": anchored_artifacts,
            "touched_gaps": touched_gaps,
            "divergence_triggered": divergence["kind"] if divergence else None,
            "agreement_triggered": agreement["kind"] if agreement else None,
            "new_edge_ids": [e["id"] for e in new_edges],
        }
        self.turns.append(delta)
        return delta

    def to_dict(self) -> dict[str, Any]:
        divergences = [p["divergence"] for p in self.places.values() if p["divergence"]]
        agreements = [p["agreement"] for p in self.places.values() if p["agreement"]]
        eig_gaps = self.compute_eig_gaps()
        anchored_count = sum(1 for a in self.artifacts.values() if a["status"] != "orphan")
        dual_nodes = sum(
            1
            for p in self.places.values()
            if p["perspectives"]["child"]["turn_ids"] and p["perspectives"]["parent"]["turn_ids"]
        )
        return {
            "schema_version": "dual-memory-graph-v1",
            "dataset_id": self.dataset_id,
            "summary": {
                "turns_ingested": len(self.turns),
                "places_total": len(self.places),
                "dual_perspective_places": dual_nodes,
                "divergences_detected": len(divergences),
                "convergent_anchors": len(agreements),
                "edges_total": len(self.edges),
                "artifacts_anchored": anchored_count,
                "artifacts_total": len(self.artifacts),
                "top_eig_gap_id": eig_gaps[0]["id"] if eig_gaps else None,
                "top_eig_priority": eig_gaps[0]["priority_score"] if eig_gaps else 0.0,
            },
            "places": list(self.places.values()),
            "people": list(self.people_nodes.values()),
            "edges": self.edges,
            "divergences": divergences,
            "agreements": agreements,
            "artifacts": list(self.artifacts.values()),
            "eig_gaps": eig_gaps,
            "turn_deltas": self.turns,
        }


def run_pipeline(stream_path: Path, artifacts_path: Path) -> DualMemoryGraphBuilder:
    artifacts_payload = json.loads(artifacts_path.read_text(encoding="utf-8"))
    builder = DualMemoryGraphBuilder(artifacts_payload)
    for raw_line in stream_path.read_text(encoding="utf-8").splitlines():
        line = raw_line.strip()
        if not line:
            continue
        builder.ingest_turn(json.loads(line))
    return builder


def verify_engine(base_dir: Path) -> None:
    """Self-contained verification suite asserting graph invariants and EIG math."""
    stream_path = base_dir / "sample_stream.jsonl"
    artifacts_path = base_dir / "sample_artifacts.json"
    builder = run_pipeline(stream_path, artifacts_path)
    graph = builder.to_dict()

    # 1. All 10 turns ingested and all 5 places receive both perspectives without collapse
    assert graph["summary"]["turns_ingested"] == 10, f"Expected 10 turns, got {graph['summary']['turns_ingested']}"
    assert graph["summary"]["places_total"] == 5, f"Expected 5 places, got {graph['summary']['places_total']}"
    assert graph["summary"]["dual_perspective_places"] == 5, "All 5 coordinates should carry both Child and Parent"

    places_by_id = {p["id"]: p for p in graph["places"]}

    # 2. Time-scoped resolution keeps early North London (2004-07) separate from later North London (2011-16)
    early_nl = places_by_id["north_london_early_2004"]
    later_nl = places_by_id["north_london_later_2011"]
    assert 2005 in early_nl["perspectives"]["child"]["years_claimed"], "2005 turn must route to early North London"
    assert 2012 in later_nl["perspectives"]["child"]["years_claimed"], "2012 turn must route to later North London"
    assert 2012 not in early_nl["perspectives"]["child"]["years_claimed"], "2012 must never collapse into 2004 terrace"

    # 3. Every place node preserves distinct Child and Parent audio timestamp spans (t0 < t1)
    for pid, p in places_by_id.items():
        for spk in ("child", "parent"):
            spans = p["perspectives"][spk]["audio_spans"]
            assert len(spans) >= 1, f"{pid} missing {spk} audio spans"
            for t0, t1 in spans:
                assert t1 > t0, f"{pid} {spk} invalid span {[t0, t1]}"

    # 4. Perspective divergence & agreement checks
    divs = {d["place_id"]: d for d in graph["divergences"]}
    agrees = {a["place_id"]: a for a in graph["agreements"]}
    assert "beijing_courtyard_2000" in divs and divs["beijing_courtyard_2000"]["kind"] == "salience_split"
    assert "sussex_village_2002" in divs and divs["sussex_village_2002"]["kind"] == "salience_split"
    assert divs["sussex_village_2002"]["valence_delta"] >= 1.3, "Village should show strong emotional split"
    assert "north_london_early_2004" in divs and divs["north_london_early_2004"]["kind"] == "salience_split"
    assert "north_london_later_2011" in agrees and agrees["north_london_later_2011"]["kind"] == "convergent_anchor"
    assert "north_london_later_2011" not in divs, "Council flat should register as agreement, not divergence"

    # 5. Tier 1 EXIF temporal clash on Docklands locks canonical year 2021 while preserving Child claim 2020
    assert "docklands_flat_2021" in divs and divs["docklands_flat_2021"]["kind"] == "temporal_clash"
    dl_div = divs["docklands_flat_2021"]
    assert dl_div["canonical_year"] == 2021, f"Expected EXIF canonical year 2021, got {dl_div['canonical_year']}"
    assert dl_div["superseded_claim"] == {"speaker": "child", "years": [2020]}, "Child 2020 claim must stay preserved"
    assert 2020 in places_by_id["docklands_flat_2021"]["perspectives"]["child"]["years_claimed"]

    # 6. Sparse orphan artifacts anchored by spoken cues while gap orphans stay pending
    arts = {a["id"]: a for a in graph["artifacts"]}
    for aid in ("art_bj_01", "art_vill_01", "art_vill_02", "art_nl_01"):
        assert arts[aid]["status"] == "voice_anchored", f"Expected {aid} voice_anchored, got {arts[aid]['status']}"
    for aid in ("art_gap_08a", "art_gap_08b", "art_gap_09c"):
        assert arts[aid]["status"] == "orphan", f"Expected {aid} still orphan before 2008-2010 turn"

    # 7. EIG ranking prioritizes 2008-2010 North London void above village scan & high-sensitivity Beijing departure
    gaps = graph["eig_gaps"]
    assert gaps[0]["id"] == "gap_2008_2010_bridge", f"Expected gap_2008_2010_bridge #1, got {gaps[0]['id']}"
    assert gaps[0]["priority_score"] > gaps[1]["priority_score"] >= gaps[2]["priority_score"]
    bj_gap = next(g for g in gaps if g["id"] == "gap_2001_departure_week")
    assert bj_gap["trust_cost"] > gaps[0]["trust_cost"], "Sensitive Beijing departure gap must carry higher trust cost"

    # 8. Live custom spoken note test (exact example from spec) + gap-shrinking verification
    custom_delta = builder.ingest_turn({
        "turn_id": "t11_custom",
        "speaker": "child",
        "t0": 180.0,
        "t1": 191.4,
        "text": "Wait, in 2005 we actually walked through the park every Tuesday after school.",
    })
    assert custom_delta["resolved_place_id"] == "north_london_early_2004", "Custom 2005 park turn must wire to early North London"
    assert "corner park walk" in custom_delta["extracted_details"]
    assert "tuesday park walk" in custom_delta["extracted_details"]
    assert [180.0, 191.4] in builder.places["north_london_early_2004"]["perspectives"]["child"]["audio_spans"]

    # 9. Verify addressing the top EIG gap shrinks its entropy and materializes a provisional node
    eig_before = gaps[0]["eig_bits"]
    bridge_delta = builder.ingest_turn({
        "turn_id": "t12_bridge",
        "speaker": "parent",
        "t0": 195.0,
        "t1": 210.2,
        "text": "In 2009 we spent a winter on the interim hill estate near the brick steps before the council flat.",
    })
    assert bridge_delta["resolved_place_id"] == "interim_north_london_2008"
    updated_gaps = {g["id"]: g for g in builder.compute_eig_gaps()}
    assert updated_gaps["gap_2008_2010_bridge"]["eig_bits"] < eig_before, "Addressing 2009 bridge must reduce EIG"

    print(
        f"PASS dual-memory-graph verify: 9/9 assertions passed "
        f"(places={graph['summary']['places_total']}, divergences={graph['summary']['divergences_detected']}, "
        f"agreements={graph['summary']['convergent_anchors']}, top_gap={gaps[0]['id']} S={gaps[0]['priority_score']})"
    )


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Dual-perspective background memory graph builder (PoC 2)")
    base_dir = Path(__file__).resolve().parent
    parser.add_argument("--stream", type=Path, default=base_dir / "sample_stream.jsonl", help="Input transcript JSONL")
    parser.add_argument("--artifacts", type=Path, default=base_dir / "sample_artifacts.json", help="Input artifacts JSON")
    parser.add_argument("--out", type=Path, default=base_dir / "memory_graph.json", help="Output memory graph JSON")
    parser.add_argument("--verify", action="store_true", help="Run built-in verification assertions")
    args = parser.parse_args(argv)

    if args.verify:
        verify_engine(base_dir)
        return 0

    builder = run_pipeline(args.stream, args.artifacts)
    output = builder.to_dict()
    args.out.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
    s = output["summary"]
    print(
        f"Built {args.out.name}: {s['turns_ingested']} turns -> {s['places_total']} places "
        f"({s['divergences_detected']} divergences, {s['convergent_anchors']} agreements, "
        f"{s['artifacts_anchored']}/{s['artifacts_total']} artifacts anchored, top gap={s['top_eig_gap_id']})"
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
