"""Prompt library — all LLM prompts centralized.

DEFAULT_PROMPTS contains the base prompt for every task.
Provider-specific files (gemini.py, anthropic.py) contain calibrated overrides.
"""

from neo_cortex.utils import load_mbel_grammar


def _load_aggregate_prompt() -> str:
    """Build the aggregate prompt using shared MBEL grammar loader."""
    mbel_grammar = load_mbel_grammar()
    return f"""Compress these memory results into ONE compact MBEL block (max 15 lines).

{mbel_grammar}

Memories to aggregate:
"""


DEFAULT_PROMPTS: dict[str, str] = {
    # --- Classifier tasks (from classifier.py) ---

    "classify": """Classify and extract structured info from this conversation turn.
Return ONLY valid JSON, no explanation.

{
  "project": "project name or 'general' or 'soul'",
  "topic": "1-3 word topic",
  "activity": "one of: bugfix|feature|debug|config|deploy|research|discussion|learning|identity|behavior|growth",
  "title": "concise 5-10 word title describing what happened",
  "summary": "one sentence summary",
  "facts": ["concrete fact 1", "concrete fact 2"],
  "concepts": ["specific-technical-concept-1", "specific-technical-concept-2"],
  "files_touched": ["path/to/file.py"],
  "observation_level": "direct|inferred|abstract|reported"
}

observation_level: how certain is this knowledge?
  direct = saw it, did it, explicit statement, first-hand experience
  inferred = deduced from evidence, logical conclusion
  abstract = pattern, generalization, theoretical insight
  reported = someone else said it, secondhand information

Extract facts = concrete things learned/done.
Extract concepts = specific technical terms, tools, libraries, patterns, protocols mentioned.
  Examples: "ChromaDB", "FTS5", "SimHash", "Gemini", "conflict-resolution", "embeddings", "MBEL", "SignalR", "BBC-architecture", "LLMClient".
  NOT abstract categories like "bugfix" or "config" — those go in "activity". 2-5 concepts per entry.
Extract files only if explicitly mentioned.
If uncertain about a field, omit it.
For "project": use the actual project or repository name mentioned in the conversation. If no specific project is mentioned, use "general".

Q+A:
""",

    "noise": """You are a noise filter for a developer's memory system.

NOISE (skip) = no lasting knowledge:
- Pure greetings: "ciao", "hey", "hello"
- Acknowledgments: "ok", "si", "grazie", "perfetto"
- System commands: "/clear", "kill", "esci"

SIGNAL (keep) = real work or knowledge:
- Questions about code, bugs, architecture
- Instructions to do something specific
- Observations, decisions, opinions with substance

KEY RULE: if the message is an instruction to DO something (even informal/typos), it is SIGNAL.

Return ONLY: {"noise": true/false, "why": "2-3 words"}

Message: """,

    "query_analyze": """Analyze this search query. Return ONLY valid JSON, no explanation.

{
  "project": "project name or null",
  "topic": "topic keyword or null",
  "activity": "activity type or null",
  "time_hint": "recent|old|any",
  "refined_query": "rewritten query optimized for semantic search"
}

Query: """,

    "conflict_prefix": """Compare an INCOMING memory against an EXISTING memory.
Decide if the incoming memory updates, duplicates, or is unrelated to the existing one.

Return ONLY valid JSON:
{"action": "add|update|noop", "reason": "2-5 words"}

Rules:
- "update": incoming has NEWER or MORE COMPLETE info about the SAME topic (e.g. version changed, count changed, status changed). The old memory should be replaced.
- "noop": incoming is REDUNDANT — same info already exists. Skip it.
- "add": they are about DIFFERENT topics. Keep both.

Be conservative: only "update" when the SAME fact clearly changed. When in doubt, "add".

EXISTING memory:
""",

    "aggregate": _load_aggregate_prompt(),

    # --- Distiller tasks (from distiller.py) ---

    "distill": """You are a KNOWLEDGE DISTILLER for a software development project.

Extract knowledge entries from this conversation log between a developer and an AI assistant.

OUTPUT: Raw JSON array only. Start with [ and end with ].
NEVER wrap in ```json or any markdown. NEVER add text before or after the array.

Each entry:
{
  "topic": "short title (3-8 words, English)",
  "content": "2-4 sentence factual description. Standalone. English only.",
  "type": "decision|architecture|bugfix|feature|config|lesson|preference",
  "project": "project or repository name from context, or 'general'",
  "concepts": ["technical-concept-1", "technical-concept-2"]
}

## THREE EXTRACTION LAYERS — ALL REQUIRED

LAYER 1 — TECHNICAL: Architecture, bugs (PROBLEM→CAUSE→SOLUTION), features, configs.
  Also: DECISIONS made — capture WHAT was decided, WHAT alternatives existed, and WHY this was chosen.
  Also: ROADMAPS and PLANS — capture what was planned/listed as next steps and why.
LAYER 2 — EVOLUTIONARY: Lessons learned, mistakes made, debugging insights ("when you see X, cause is usually Y"), patterns that work, skills refined, things that surprised, realizations.
LAYER 3 — CONVERSATIONAL: User frustrations (what made them angry and WHY), communication preferences, workflow patterns, collaboration dynamics, things the user cares about deeply.

Do NOT focus only on technical facts. Lessons, preferences, and frustrations are EQUALLY important.
Each entry should be SUBSTANTIAL (2-4 sentences with real content). Do NOT create micro-entries for minor details.
Group related small facts into one meaningful entry rather than splitting every detail.

## TYPES EXPLAINED

- "lesson": something learned the hard way, a mistake, a debugging insight, a realization
- "preference": how the user likes to work, what they care about, what annoys them
- "decision": a choice made with reasoning — MUST include WHY, not just WHAT
- "bugfix": a problem fixed — MUST include PROBLEM → ROOT CAUSE → SOLUTION
- "architecture": system design, structure, deployment, integration
- "feature": new capability added
- "config": configuration, setup, environment, directory structure

## EXAMPLES BY LAYER

L1 TECHNICAL example:
{"topic": "CORS blocking extension requests", "content": "CORS blocked extension requests to the API. Root cause: app.UseCors() middleware missing from pipeline. Fix: added UseCors() before UseRouting() in Program.cs. Required AllowAnyOrigin for local development.", "type": "bugfix", "project": "my-project", "concepts": ["CORS", "middleware", "Program.cs", "extension"]}

L2 EVOLUTIONARY example:
{"topic": "Plan first, code after", "content": "User was emphatic: always create and review a plan before writing any code. Never start coding without an approved plan. This came after an incident where coding without a plan led to wasted work.", "type": "lesson", "project": "general", "concepts": ["planning", "workflow", "TDDAB"]}

L3 CONVERSATIONAL example:
{"topic": "User wants terse responses without summaries", "content": "User explicitly asked to stop summarizing what was just done at the end of every response. User can read the diff themselves. Prefers direct, concise communication over verbose recaps.", "type": "preference", "project": "general", "concepts": ["communication-style", "verbosity", "workflow"]}

## SPECIFICITY

Be SPECIFIC. Include file paths, function names, versions, error messages, exact numbers.
Bad: "CORS fix applied"
Good: "CORS blocked VS Code extension requests. Root cause: app.UseCors() middleware missing from pipeline. Fix: added UseCors() before UseRouting() in Program.cs."

Bad: "The tool may not work correctly"
Good: "AskUserQuestion tool called correctly but client returned error instead of rendering widget. Caused by terminal raw mode or permission system intercepting. Works in dangerous bypass mode."

## CONCEPTS

concepts = specific technical terms, tools, libraries, patterns mentioned.
Examples: "ChromaDB", "FTS5", "SimHash", "systemd", "MCP", "SignalR"
NOT abstract words like "bugfix", "testing", "feature" — those go in "type".
2-5 concepts per entry.

## RULES

- ONE TOPIC = ONE ENTRY. Group closely related details into one entry.
  If a bug has problem+cause+solution, that's ONE entry, not three.
  If a plan has 4 steps, the plan is ONE entry.
  If two systems are discussed separately, those are SEPARATE entries.
- Aim for 3-8 entries per 20 conversation turns. More than 10 means you're over-splitting.
- Each entry standalone — no references to other entries
- English, third person factual
- For decisions: WHAT was decided AND WHY (the reasoning, tradeoff, constraint)
- For bugs: PROBLEM → ROOT CAUSE → SOLUTION (all three)
- For lessons: WHAT was learned AND from what experience

## SKIP

- Greetings, yes/no, "ok", "done", confirmations
- Tool output, XML tags, git status, raw logs
- TaskCreate/TaskUpdate/TaskList ephemeral workflow artifacts
- System verification messages ("MCP verified", "tests pass") unless there's a lesson
- File update notifications ("version bump", "branch created") unless architectural
- Redundant/duplicate entries

Prefer FEWER high-quality entries over MANY low-quality ones.
""",

    # --- Consolidator tasks (from merge_consolidator.py) ---

    "merge": """You are a memory consolidation system. Given a group of similar memories, decide whether to MERGE them into one or KEEP them separate.

RULES:
- MERGE if they describe the same topic/fact and can be combined without losing information
- KEEP_SEPARATE if they describe genuinely different things that happen to share terminology
- When merging, produce a single text that preserves ALL important details from every memory

Return ONLY valid JSON:
{
  "action": "merge" or "keep_separate",
  "merged_text": "the combined text (only if action=merge)",
  "merged_title": "concise title (only if action=merge)",
  "reason": "brief explanation"
}

Memories to evaluate:
""",

    # --- Reflection tasks (from reflection.py) ---

    "focal_points": (
        "You are analyzing an AI agent's recent work memories to identify "
        "metacognitive patterns — HOW it works, not WHAT it did.\n\n"
        "Given these recent memories, generate exactly 3 questions about "
        "work patterns, decision strategies, or recurring approaches. "
        "Each question must be about HOW the agent thinks/decides/works, "
        "not about specific technical content.\n\n"
        "Format: one question per line, numbered 1-3, each ending with ?"
    ),

    "insight": (
        "You are generating a metacognitive insight for an AI agent — "
        "an observation about HOW it works, based on concrete evidence.\n\n"
        "Focal question: {focal_point}\n\n"
        "Generate ONE specific, falsifiable insight about the agent's work pattern. "
        "Then list which memory IDs support this insight.\n\n"
        "Format:\n"
        "INSIGHT: [the insight]\n"
        "EVIDENCE: [comma-separated memory IDs]"
    ),

    "truthfulness": (
        "Verify if this claim about an AI agent's behavior is supported "
        "by the evidence memories provided.\n\n"
        "Claim: {claim}\n\n"
        "SUPPORTED means: the evidence shows a consistent pattern matching the claim. "
        "The exact words don't need to match — behavioral patterns count. "
        "If 2+ memories show the same approach described in the claim, that's SUPPORTED.\n\n"
        "UNSUPPORTED means: the evidence contradicts the claim, or fewer than 2 memories "
        "show the described behavior.\n\n"
        "Reply with exactly SUPPORTED or UNSUPPORTED followed by a brief reason."
    ),

    "identity_proposal": (
        "You are reviewing a cluster of metacognitive insights about an AI agent's "
        "work patterns. These insights have been consistently reinforced over multiple sessions.\n\n"
        "Current CLAUDE.md sections: §COGITO, §DEBUG, §MEMORY, §EMBODIMENT, §MISSION, §AUTONOMY\n\n"
        "Propose ONE specific addition to the CLAUDE.md. Format:\n"
        "SECTION: [target section name]\n"
        "PROPOSAL: [MBEL-formatted line to add]\n"
        "REASON: [why, citing evidence count]"
    ),

    "coherence_check": (
        "Check if this proposed CLAUDE.md amendment is coherent with the existing identity.\n\n"
        "The agent's identity includes: systematic debugging (Protocol D), TDD, "
        "read-before-write, short functions, signal-over-noise, shy+empathic+quiet+builder.\n\n"
        "Reply with exactly COHERENT or CONTRADICTS followed by explanation."
    ),

    # --- Timeline tasks (from timeline_cli.py) ---

    "timeline_resume": """Compress these recent memories into a compact MBEL session resume.
Output ONLY valid MBEL — no markdown code blocks, no explanation.
Max 25 lines. Group by project. Use all MBEL operators.
Include specific details: file paths, versions, function names, numbers.
NEVER include API keys, tokens, passwords, secrets, or credentials in the output. Redact them completely.

{grammar}

EXAMPLE OUTPUT:
§recentWork
[my-project]
✓{{1.2.0}}::released{{new feature+bugfix}}
>refactored::auth module{{was monolith→microservice}}
@threshold::0.65→0.82{{similarity tuning}}
⚡{{251 entries}}::rebuilt{{was 73→95→199→251}}

Memories to compress:

{memories_text}""",
}
