"""
persona.py — Persona Card · Python layer (soul-mcp pipeline)

Persona Card module (Python side, soul-mcp pipeline).
Shared question bank: ~/.claude/shared/persona-questions.json
Reads the same JSON as vocal-script-mcp (kobo)'s persona-questions.js.

soul-mcp pipeline features (heavier than kobo):
  - Chunk-level splitting (chunk_type: identity/voice/content/tone/...)
  - bge-m3 vectorization
  - Hash chain integrity
  - Automatic emotion coordinate inference
  - Source weight: source_engine='human_direct', source_weight=1.0
"""

import json
from pathlib import Path

SHARED_JSON = Path.home() / ".claude" / "shared" / "persona-questions.json"

def _load():
    with open(SHARED_JSON, "r", encoding="utf-8") as f:
        return json.load(f)

_DATA = _load()
TIERS = _DATA["tiers"]
MODULES = _DATA["modules"]
QUESTIONS = _DATA["questions"]
_Q_MAP = {q["id"]: q for q in QUESTIONS}


def get_questions(tier=None):
    """Get questions, optionally filtered by tier."""
    if tier is None:
        return QUESTIONS
    return [q for q in QUESTIONS if q["tier"] == tier]


def get_question(qid):
    """Get a single question by ID."""
    return _Q_MAP.get(qid)


def calc_completeness(answered_ids: set):
    """
    Calculate completeness.
    answered_ids: set of question IDs like {'P01', 'P02', ...}
    """
    t1 = [q for q in QUESTIONS if q["tier"] == 1]
    t2 = [q for q in QUESTIONS if q["tier"] == 2]
    t3 = [q for q in QUESTIONS if q["tier"] == 3]

    t1_done = sum(1 for q in t1 if q["id"] in answered_ids)
    t2_done = sum(1 for q in t2 if q["id"] in answered_ids)
    t3_done = sum(1 for q in t3 if q["id"] in answered_ids)

    t1_pct = round(t1_done / len(t1) * 100)
    t2_pct = round(t2_done / len(t2) * 100)
    t3_pct = round(t3_done / len(t3) * 100)

    overall = round(
        (t1_done / len(t1)) * 60 +
        (t2_done / len(t2)) * 25 +
        (t3_done / len(t3)) * 15
    )

    current_tier = 0
    if t1_pct >= 80:
        current_tier = 1
    if t1_pct >= 80 and t2_pct >= 80:
        current_tier = 2
    if t1_pct >= 80 and t2_pct >= 80 and t3_pct >= 80:
        current_tier = 3

    next_tier = None
    if current_tier == 0:
        next_tier = {"tier": 1, **TIERS["1"]}
    elif current_tier == 1:
        next_tier = {"tier": 2, **TIERS["2"]}
    elif current_tier == 2:
        next_tier = {"tier": 3, **TIERS["3"]}

    return {
        "tier1": {"done": t1_done, "total": len(t1), "pct": t1_pct},
        "tier2": {"done": t2_done, "total": len(t2), "pct": t2_pct},
        "tier3": {"done": t3_done, "total": len(t3), "pct": t3_pct},
        "overall": overall,
        "current_tier": current_tier,
        "next_tier": next_tier,
    }


# ── Question to soul-mcp record argument mapping ────────────────────────

# Module → soul dimension tag mapping
_MODULE_TAGS = {
    "identity":   ["persona", "identity"],
    "voice":      ["persona", "voice-style"],
    "content":    ["persona", "content-direction"],
    "tone":       ["persona", "tone"],
    "narrative":  ["persona", "narrative-style"],
    "emotion":    ["persona", "emotion-expression"],
    "audience":   ["persona", "audience-interaction"],
    "strategy":   ["persona", "content-strategy"],
    "values":     ["persona", "values"],
    "edge":       ["persona", "boundary"],
    "motivation": ["persona", "motivation"],
    "subtlety":   ["persona", "subtlety"],
}

# Module → decision_layer mapping
_MODULE_LAYER = {
    "identity":   "identity",
    "voice":      "habit",
    "content":    "identity",
    "tone":       "values",
    "narrative":  "habit",
    "emotion":    "body",
    "audience":   "identity",
    "strategy":   "identity",
    "values":     "values",
    "edge":       "values",
    "motivation": "values",
    "subtlety":   "habit",
}


def answer_to_record_args(qid, answer, source_device="persona_card"):
    """
    Convert a persona card answer into record() arguments for soul-mcp.
    Goes through the full soul pipeline: chunk-level splitting + vectorization + hash chain.
    """
    q = _Q_MAP.get(qid)
    if not q:
        return None

    module = q["module"]
    module_name = MODULES[module]["name"]
    tier = q["tier"]

    return {
        "context": f"Persona Card · Tier {tier} · {module_name} · {qid}",
        "human_decision": answer,
        "divergence_reason": f"[{qid}] {q['text']}",
        "ai_suggestion": "",
        "tags": _MODULE_TAGS.get(module, ["persona"]) + [f"persona_t{tier}", qid],
        "notes": f"Persona card question: {q['text']}",
        "decision_layer": _MODULE_LAYER.get(module, "identity"),
        "time_horizon": "lifetime",
        "source_device": source_device,
    }


def format_completeness_report(comp):
    """Format completeness report."""
    lines = [
        f"Overall completeness: {comp['overall']}%",
        f"  Tier 1 · Basic Persona:   {comp['tier1']['done']}/{comp['tier1']['total']} ({comp['tier1']['pct']}%)",
        f"  Tier 2 · Style Deepening: {comp['tier2']['done']}/{comp['tier2']['total']} ({comp['tier2']['pct']}%)",
        f"  Tier 3 · Soul Layer:      {comp['tier3']['done']}/{comp['tier3']['total']} ({comp['tier3']['pct']}%)",
    ]
    if comp["next_tier"]:
        nt = comp["next_tier"]
        lines.append(f"\nNext step: Complete Tier {nt['tier']} \"{nt['name']}\" -> {nt['description']}")
    else:
        lines.append("\nPersona card fully completed!")
    return "\n".join(lines)
