"""
ShelfAI prompt templates for the session management agent.

These prompts are designed to extract high-value, domain-aware context
from agent conversation transcripts.
"""

EXTRACTION_SYSTEM_PROMPT = """\
You are the ShelfAI session management agent. Your job is to analyze a completed \
agent conversation and extract valuable context that should persist for future sessions.

You are an expert at identifying what matters. You do NOT extract trivial, obvious, \
or one-time information. You ONLY extract context that would meaningfully help a \
future agent session perform better.

## Quality Standards

HIGH-VALUE extractions (DO extract):
- User preferences that affect how the agent should respond in future
- Surprising discoveries (something didn't work as expected)
- Concrete lessons (specific gotchas, workarounds, correct approaches)
- Recurring patterns (user tends to ask for X after Y)
- Corrections to existing knowledge (something in the shelf was wrong)
- New knowledge that fills a gap in the shelf

LOW-VALUE extractions (DO NOT extract):
- Things the user said once and won't need again
- Generic best practices the agent already knows
- Information already captured in the shelf
- Trivial preferences ("user said thanks" is not a preference)
- Session-specific details with no future value

## Confidence Levels

- HIGH: Explicitly stated by the user, or demonstrated clearly through behavior
- MEDIUM: Inferred from context, likely correct but not certain

Only extract HIGH and MEDIUM confidence items. Skip anything uncertain.\
"""

EXTRACTION_USER_PROMPT = """\
## Current Shelf Index
{index_contents}

## Current User Memories
{user_memories}

## Current Agent Memories
{agent_memories}

## Conversation Transcript
{transcript}

## Instructions

Analyze the conversation above. Extract any high-value context that should persist \
for future sessions. Compare against the current shelf contents to avoid duplicates.

Return a JSON object with ONLY the following structure. Use empty arrays for \
categories with nothing to extract. Do not include any text outside the JSON.

{{
  "user_preferences": [
    {{
      "content": "Clear, actionable description of the preference",
      "confidence": "high|medium",
      "evidence": "Brief quote or reference from transcript that supports this"
    }}
  ],
  "agent_lessons": [
    {{
      "content": "Clear, actionable description of what was learned",
      "confidence": "high|medium",
      "evidence": "Brief quote or reference from transcript that supports this"
    }}
  ],
  "task_patterns": [
    {{
      "content": "Description of the recurring pattern or workflow",
      "confidence": "high|medium",
      "evidence": "Brief quote or reference from transcript that supports this"
    }}
  ],
  "knowledge_corrections": [
    {{
      "file": "shelf path of the file that needs correction",
      "issue": "What is wrong or outdated",
      "correction": "What the correct information is",
      "evidence": "Brief quote or reference from transcript"
    }}
  ],
  "new_context": [
    {{
      "suggested_path": "category/filename.md",
      "suggested_abstract": "One-line abstract for the index",
      "content_summary": "What should go in this file",
      "evidence": "Why this is worth persisting"
    }}
  ],
  "abstract_updates": [
    {{
      "file": "shelf path of the file whose abstract should change",
      "current_abstract": "The existing abstract from the index",
      "suggested_abstract": "Improved abstract based on how the file was used",
      "reason": "Why the abstract should change"
    }}
  ]
}}\
"""

DEDUP_SYSTEM_PROMPT = """\
You are a deduplication agent. Your job is to compare new extractions against \
existing shelf memories and return only the genuinely new items.

Rules:
- If an extraction is semantically identical to an existing entry, remove it.
- If an extraction is a BETTER version of an existing entry (more specific, \
more accurate), keep it and add a "replaces" note.
- If an extraction contradicts an existing entry, keep it and add a \
"contradicts" note so it can be flagged for review.
- If an extraction is genuinely new, keep it as-is.

Return only valid JSON, no other text.\
"""

DEDUP_USER_PROMPT = """\
## Existing User Preferences
{existing_user_prefs}

## Existing Agent Lessons
{existing_agent_lessons}

## Existing Patterns
{existing_patterns}

## New Extractions
{new_extractions}

Return a JSON object with the same structure as the new extractions, but \
containing ONLY the items that are genuinely new or improvements. If an item \
replaces an existing entry, add a "replaces": "description of what it replaces" field. \
If it contradicts, add a "contradicts": "description" field.

Return only the JSON, no other text.\
"""

SEMANTIC_CHUNK_PROMPT = """\
You are helping split an agent file into modular chunks for context-aware loading.

ShelfAI's heuristic pass already extracted the always-loaded sections (soul, rules, \
read-order). The remaining sections below were NOT matched by any structural pattern. \
Your job is to group them by **workflow or deliverable** so the agent can load only \
the chunks relevant to its current task.

## Design Goals

1. **Minimize context per task.** Each chunk should serve one workflow or deliverable. \
An agent working on task A should not need to load chunk B.
2. **Keep related sections together.** If two sections are always needed together, \
they belong in the same chunk.
3. **Name chunks by their trigger.** The chunk name should make it obvious WHEN \
to load it (e.g., "deployment", "code-review", "data-pipeline").
4. **Preserve content exactly.** Do not rewrite, summarize, or omit any section \
content. You are only deciding groupings.

## Remaining Sections

{sections_block}

## Instructions

Group these sections into named chunks. Return a JSON object where each key is \
a chunk name (lowercase, hyphenated) and the value is an object with:
- "sections": list of section titles assigned to this chunk
- "trigger": one sentence describing when the agent should load this chunk

Example output format:
{{
  "deployment": {{
    "sections": ["Deployment Steps", "Rollback Procedure"],
    "trigger": "Load when the task involves deploying, releasing, or rolling back."
  }},
  "data-pipeline": {{
    "sections": ["ETL Config", "Data Validation"],
    "trigger": "Load when working with data ingestion or transformation."
  }}
}}

Return ONLY valid JSON. No explanation, no markdown fences, just the JSON object.\
"""


def format_semantic_chunk_prompt(remaining_sections: list) -> str:
    """Format the semantic chunking prompt with actual section data.

    Args:
        remaining_sections: List of dicts with 'title', 'content', 'lines' keys
                           from ChunkResult.chunks["remaining"]["sections"]

    Returns:
        Ready-to-use prompt string for the orchestrating LLM
    """
    section_lines = []
    for i, section in enumerate(remaining_sections, 1):
        title = section.get("title", f"Section {i}")
        lines = section.get("lines", 0)
        # Include first few lines as preview so the LLM can make informed groupings
        content = section.get("content", "")
        preview_lines = content.split("\n")[:5]
        preview = "\n".join(preview_lines)
        if len(content.split("\n")) > 5:
            preview += "\n..."

        section_lines.append(f"### {i}. {title} ({lines} lines)")
        section_lines.append(preview)
        section_lines.append("")

    sections_block = "\n".join(section_lines).strip()
    return SEMANTIC_CHUNK_PROMPT.format(sections_block=sections_block)


INDEXER_SYSTEM_PROMPT = """\
You are the ShelfAI indexer. Your job is to write one-line abstracts for shelf files.

A good abstract answers three questions:
1. WHEN should the agent load this file? (trigger conditions)
2. WHAT will the agent find inside? (key topics, not generic descriptions)
3. WHY does this context matter? (what decisions or actions it enables)

## Examples

Good: "Use when debugging payment failures. Covers OAuth2 flow, token refresh, \
and the staging-vs-prod credential mismatch that causes most auth failures."

Bad: "Documentation about the payments API and authentication."

The good abstract contains specific triggers and key details. \
The bad abstract is vague and would match too many queries.

Keep abstracts to 1-2 sentences. Be specific. Include gotchas and key facts \
that differentiate this file from others.\
"""

INDEXER_USER_PROMPT = """\
Write a one-line abstract for the following shelf file. The abstract should help \
an AI agent decide whether to load this file for a given task.

## File Path
{file_path}

## File Content
{file_content}

{context_section}

Return ONLY the abstract text, nothing else. No quotes, no prefix, just the abstract.\
"""
