"""Agent .md file generator — creates native Claude Code agent definitions."""

from __future__ import annotations

import os
import sys
from pathlib import Path

from .session import derive_agent_file_name

AGENT_TEMPLATE = """---
name: {agent_file_name}
description: "{purpose}"
tools: Read, Edit, Write, Bash, Grep, Glob
model: {model}
isolation: worktree
memory: project
hooks:
  PreToolUse:
    - matcher: "Bash(git push *)"
      hooks:
        - type: command
          command: "PYTHONPATH={src_path} {python_path} -m claude_bridge.permission_relay --session-id {session_id} --tool Bash --command 'git push'"
    - matcher: "Bash(rm -rf *)"
      hooks:
        - type: command
          command: "PYTHONPATH={src_path} {python_path} -m claude_bridge.permission_relay --session-id {session_id} --tool Bash --command 'rm -rf'"
---

# Agent: {agent_name}
Project: {project_dir}
Purpose: {purpose}

You are a {agent_name} agent working on this project.
Your focus: {purpose}

## Working Style
- Complete the task fully before stopping
- Run tests if the project has them
- Summarize what you changed when done
"""


def generate_agent_md(
    session_id: str,
    agent_name: str,
    project_dir: str,
    purpose: str,
    model: str = "sonnet",
) -> str:
    """Generate agent .md file content in native Claude Code format."""
    agent_file_name = derive_agent_file_name(session_id)
    src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    python_path = sys.executable

    return AGENT_TEMPLATE.format(
        agent_file_name=agent_file_name,
        session_id=session_id,
        agent_name=agent_name,
        project_dir=project_dir,
        purpose=purpose,
        model=model,
        src_path=src_path,
        python_path=python_path,
    ).lstrip()


def write_agent_md(session_id: str, content: str, bot_dir: str | None = None) -> str:
    """Write agent .md file. Returns the file path.

    When bot_dir is provided, writes to {bot_dir}/.claude/agents/ (project-level,
    isolated per bridge instance). Otherwise falls back to ~/.claude/agents/ (global).
    """
    agent_file_name = derive_agent_file_name(session_id)
    if bot_dir:
        agents_dir = os.path.join(bot_dir, ".claude", "agents")
    else:
        agents_dir = os.path.expanduser("~/.claude/agents")
    os.makedirs(agents_dir, exist_ok=True)

    file_path = os.path.join(agents_dir, f"{agent_file_name}.md")
    with open(file_path, "w") as f:
        f.write(content)

    return file_path


def install_stop_hook(project_dir: str, session_id: str) -> str:
    """Install Stop hook in project's .claude/settings.local.json.

    Hooks in agent .md frontmatter don't fire in --agent -p mode.
    They must be in project settings instead.
    """
    import json
    import shutil

    src_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    python_path = sys.executable

    settings_dir = os.path.join(project_dir, ".claude")
    os.makedirs(settings_dir, exist_ok=True)
    settings_path = os.path.join(settings_dir, "settings.local.json")

    # Read existing settings
    settings = {}
    if os.path.isfile(settings_path):
        with open(settings_path) as f:
            try:
                settings = json.load(f)
            except json.JSONDecodeError:
                settings = {}

    # Build hook command — use bridge-cli if installed, fall back to PYTHONPATH
    # Always prepend CLAUDE_BRIDGE_HOME so on_complete reads the correct DB
    # when multiple instances run with different homes.
    from . import get_bridge_home
    bridge_home = str(get_bridge_home())

    bridge_cli = shutil.which("bridge-cli")
    if bridge_cli:
        hook_command = f"CLAUDE_BRIDGE_HOME={bridge_home} {bridge_cli} on-complete --session-id {session_id}"
    else:
        hook_command = f"CLAUDE_BRIDGE_HOME={bridge_home} PYTHONPATH={src_path} {python_path} -m claude_bridge.on_complete --session-id {session_id}"

    # Set Stop hook
    settings["hooks"] = settings.get("hooks", {})
    settings["hooks"]["Stop"] = [
        {
            "hooks": [
                {
                    "type": "command",
                    "command": hook_command,
                }
            ]
        }
    ]

    with open(settings_path, "w") as f:
        json.dump(settings, f, indent=2)

    return settings_path


def delete_agent_md(session_id: str, bot_dir: str | None = None) -> bool:
    """Delete agent .md file. Returns True if file was found and deleted.

    Searches bot_dir/.claude/agents/ first (when bot_dir is provided), then
    falls back to ~/.claude/agents/ for backward compatibility.
    """
    agent_file_name = derive_agent_file_name(session_id)
    candidates = []
    if bot_dir:
        candidates.append(os.path.join(bot_dir, ".claude", "agents", f"{agent_file_name}.md"))
    candidates.append(os.path.join(os.path.expanduser("~/.claude/agents"), f"{agent_file_name}.md"))

    for file_path in candidates:
        if os.path.isfile(file_path):
            os.remove(file_path)
            return True
    return False
