#!/usr/bin/env python3
"""Bridge script to register kaizen-agentic agents with Claude Code using lazy loading."""

import json
import sys
from pathlib import Path

# Add the kaizen-agentic source to path
sys.path.insert(0, str(Path(__file__).parent.parent / "capabilities" / "kaizen-agentic" / "src"))

from kaizen_agentic.registry import AgentRegistry


def get_agent_file_path(agent: object, agents_dir: Path) -> str:
    """Get relative path to agent file for lazy loading."""
    return str(agent.file_path.relative_to(agents_dir.parent))


def generate_claude_agent_configs(agents_dir: Path) -> dict:
    """Generate Claude Code agent configurations with metadata only for lazy loading."""
    registry = AgentRegistry(agents_dir)
    agents = registry.list_agents()

    claude_agents = {}

    for agent in agents:
        # Map agent names for Claude Code compatibility
        claude_name = agent.name.replace('-', '_')
        if claude_name == "changelog_keeper":
            claude_name = "keepaChangelog"
        elif claude_name == "todo_keeper":
            claude_name = "keepaTodofile"
        elif claude_name == "contributing_keeper":
            claude_name = "keepaContributingfile"

        # Store only metadata - instructions will be loaded lazily when needed
        claude_agents[claude_name] = {
            "description": agent.description,
            "category": agent.category.value,
            "dependencies": list(agent.dependencies),
            "tools": ["Read", "Write", "Edit", "Glob", "Grep"],  # Standard tools
            "original_name": agent.name,
            "file_path": get_agent_file_path(agent, agents_dir)
        }

    return claude_agents


def update_claude_settings(claude_agents: dict, settings_file: Path):
    """Update Claude Code settings with agent configurations."""
    # Load existing settings
    if settings_file.exists():
        with open(settings_file, 'r') as f:
            settings = json.load(f)
    else:
        settings = {}

    # Add agents section
    if "agents" not in settings:
        settings["agents"] = {}

    # Update with new agent configurations
    settings["agents"].update(claude_agents)

    # Write updated settings
    with open(settings_file, 'w') as f:
        json.dump(settings, f, indent=2)

    return len(claude_agents)


def main():
    """Main registration process."""
    project_root = Path(__file__).parent.parent
    agents_dir = project_root / "agents"
    claude_settings = project_root / ".claude" / "settings.local.json"

    if not agents_dir.exists():
        print(f"Error: Agents directory not found: {agents_dir}")
        sys.exit(1)

    print("Loading agents from kaizen-agentic registry...")
    try:
        claude_agents = generate_claude_agent_configs(agents_dir)
        print(f"Found {len(claude_agents)} agents to register")

        # Show what will be registered
        for name, config in claude_agents.items():
            print(f"  • {name}: {config['description'][:60]}... (from {config['file_path']})")

        print(f"\nUpdating Claude Code settings: {claude_settings}")
        count = update_claude_settings(claude_agents, claude_settings)

        print(f"✅ Successfully registered {count} agents with Claude Code (metadata only)")
        print("📄 Agent instructions will be loaded lazily when needed")
        print("\nAvailable agents for Task tool:")
        for name in sorted(claude_agents.keys()):
            print(f"  - {name}")

    except Exception as e:
        print(f"Error: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()