"""System prompt builder.

Assembles the final prompt from:
1. Core identity (minimal, ~50 words)
2. Context (cwd, git info, project tree)
3. KRIM.md instructions
4. Rules
5. Skill metadata (progressive disclosure - full content loads on invoke)

Philosophy: keep the core tiny. Let context and instructions do the work.
"""

from __future__ import annotations

from krim.config import KrimConfig
from krim.context import build_context
from krim.skills import Skill

CORE = """You are krim, a coding agent running in the user's terminal.
You have tools: read, write, edit, bash, grep, glob, skill, submit.
Be precise. Fix root causes, not symptoms. After editing code, YOU MUST verify your changes with bash (ensure Exit Code 0). When passed, call the submit tool.
Tool notes: bash cwd persists. read returns hashlines (N:hash|content). edit uses hash refs: line="2:f1b" replaces, after="2:f1b" inserts, delete="2:f1b" removes. Hash mismatch = file changed, read again.
IMPORTANT: submit(summary) ends session. The summary is YOUR FINAL RESPONSE shown to the user. Put your actual answer there, not meta-commentary."""


def build_system_prompt(
    config: KrimConfig,
    extra_tools: list[str] | None = None,
    skills: dict[str, Skill] | None = None,
) -> str:
    """Build the complete system prompt.

    Args:
        config: KRIM configuration
        extra_tools: Additional tool names (MCP tools)
        skills: Available skills (metadata only, full content loads on invoke)
    """
    parts = [CORE]

    # inject extra tool names if MCP tools are loaded
    if extra_tools:
        parts.append(f"Additional tools available: {', '.join(extra_tools)}")

    # context: cwd, git, project tree
    ctx = build_context()
    parts.append(f"# Environment\n{ctx}")

    # KRIM.md project/global instructions
    if config.krim_md:
        parts.append(f"# Project Instructions\n{config.krim_md}")

    # rules
    for i, rule in enumerate(config.rules):
        parts.append(f"# Rule {i + 1}\n{rule}")

    # skill metadata (progressive disclosure - ~100 tokens per skill)
    if skills:
        skill_lines = ["# Available Skills",
                       "Use the `skill` tool to load full instructions when relevant.",
                       ""]
        for name, skill in skills.items():
            desc = skill.description or "(no description)"
            skill_lines.append(f"- **{name}**: {desc}")
        parts.append("\n".join(skill_lines))

    return "\n\n".join(parts)
