#!/usr/bin/env python3
"""
Claude Code Integration Setup Script

Sets up complete Claude Code infrastructure for circuit-synth including:
- Agent training examples
- Memory bank with design knowledge
- Project configuration files
- Intelligent slash commands and hooks

This script handles both first-time setup and updates for PyPI installations.
"""

import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Optional


def get_package_data_dir() -> Path:
    """Get the package data directory containing examples and memory-bank"""
    try:
        import circuit_synth

        package_dir = Path(circuit_synth.__file__).parent
        return package_dir / "data"
    except Exception:
        # Development mode - look in repository structure
        script_dir = Path(__file__).parent
        repo_root = script_dir.parent.parent.parent  # ../../../
        return repo_root


def check_claude_availability() -> bool:
    """Check if Claude Code is available in the system"""
    try:
        result = subprocess.run(["which", "claude"], capture_output=True, text=True)
        return result.returncode == 0
    except Exception:
        return False


def create_claude_config(target_dir: Path) -> None:
    """Create .claude configuration file for circuit-synth"""
    claude_config = target_dir / ".claude"

    config_content = """# Claude Code Configuration for Circuit-Synth
# Generated by setup-claude-integration

# Enable real-time validation hooks
hooks:
  component-availability: true
  design-rule-check: true
  stm32-pin-validation: true
  manufacturing-readiness: true

# Memory management
memory:
  preserve_context: true
  load_examples: true
  load_memory_bank: true
"""

    claude_config.write_text(config_content)
    print(f"✅ Created Claude configuration: {claude_config}")


def copy_examples(source_dir: Path, target_dir: Path) -> None:
    """Copy agent training examples to target directory"""
    source_examples = source_dir / "examples"
    target_examples = target_dir / "examples"

    if source_examples.exists():
        if target_examples.exists():
            print(f"📁 Updating existing examples directory...")
            shutil.rmtree(target_examples)
        else:
            print(f"📁 Creating examples directory...")

        shutil.copytree(source_examples, target_examples)
        print(f"✅ Agent training examples copied to: {target_examples}")

        # Count files to show scope
        example_count = sum(1 for f in target_examples.rglob("*.py") if f.is_file())
        print(f"   📋 {example_count} example circuits available for AI training")
    else:
        print(f"⚠️  Examples directory not found at: {source_examples}")
        return False
    return True


def copy_memory_bank(source_dir: Path, target_dir: Path) -> None:
    """Copy memory bank with design knowledge to target directory"""
    source_memory = source_dir / "memory-bank"
    target_memory = target_dir / "memory-bank"

    if source_memory.exists():
        if target_memory.exists():
            print(f"🧠 Updating existing memory-bank...")
            shutil.rmtree(target_memory)
        else:
            print(f"🧠 Creating memory-bank directory...")

        shutil.copytree(source_memory, target_memory)
        print(f"✅ Design knowledge memory-bank copied to: {target_memory}")

        # Count knowledge files
        knowledge_count = sum(1 for f in target_memory.rglob("*.md") if f.is_file())
        print(f"   📚 {knowledge_count} knowledge documents available")
    else:
        print(f"⚠️  Memory-bank directory not found at: {source_memory}")
        return False
    return True


def copy_claude_md(source_dir: Path, target_dir: Path) -> None:
    """Copy CLAUDE.md with project instructions"""
    source_claude_md = source_dir / "CLAUDE.md"
    target_claude_md = target_dir / "CLAUDE.md"

    if source_claude_md.exists():
        if target_claude_md.exists():
            print(f"📄 Updating CLAUDE.md instructions...")
        else:
            print(f"📄 Creating CLAUDE.md instructions...")

        shutil.copy2(source_claude_md, target_claude_md)
        print(f"✅ Claude instructions copied to: {target_claude_md}")
    else:
        print(f"⚠️  CLAUDE.md not found at: {source_claude_md}")
        return False
    return True


def detect_environment() -> str:
    """Detect if running in CI/CD or interactive environment"""
    ci_indicators = ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "JENKINS_URL"]
    if any(os.getenv(indicator) for indicator in ci_indicators):
        return "ci"
    return "interactive"


def main(target_dir: Optional[Path] = None) -> None:
    """Setup Claude Code integration for circuit-synth"""

    if target_dir is None:
        target_dir = Path.cwd()

    print("🚀 Setting up Claude Code integration for circuit-synth...")
    print(f"📁 Target directory: {target_dir}")

    # Detect environment
    env_mode = detect_environment()
    if env_mode == "ci":
        print("🤖 CI/CD environment detected")

    # Check Claude availability
    claude_available = check_claude_availability()
    if not claude_available:
        print("⚠️  Claude Code not found in PATH")
        print("   Install Claude Code to enable AI-powered circuit design")
        print("   See: https://claude.ai/code")

    # Get source directory
    source_dir = get_package_data_dir()
    print(f"📦 Package data source: {source_dir}")

    if not source_dir.exists():
        print(f"❌ Package data directory not found: {source_dir}")
        print("   This may indicate a packaging issue.")
        sys.exit(1)

    success_count = 0
    total_steps = 3

    try:
        # Create target directory if needed
        target_dir.mkdir(parents=True, exist_ok=True)

        # Copy infrastructure files
        if copy_examples(source_dir, target_dir):
            success_count += 1
        if copy_memory_bank(source_dir, target_dir):
            success_count += 1
        if copy_claude_md(source_dir, target_dir):
            success_count += 1

        # Create configuration
        create_claude_config(target_dir)

        # Initialize Claude Code integration
        try:
            from circuit_synth import setup_claude_integration

            setup_claude_integration()
        except ImportError:
            print("⚠️  Claude Code SDK not available for full integration")
            print("   Install with: pip install circuit-synth[claude]")

        print(
            f"\n🎯 Claude Code integration setup complete! ({success_count}/{total_steps} components)"
        )

        if claude_available:
            print("\n🤖 Available agent:")
            print("   - circuit-synth: Circuit-synth code generation specialist")

            print("\n⚡ Available shortcut:")
            print("   - /check-manufacturing: Real-time component availability")

            print("\n🔧 Real-time validation enabled:")
            print("   - Component availability checking")
            print("   - Circuit design rule validation")
            print("   - STM32 pin assignment verification")
            print("   - Manufacturing readiness assessment")

            print(f"\n✨ Ready for AI-powered circuit design!")
            print("   Try: Ask Claude to design an STM32 development board")
        else:
            print(f"\n✅ Circuit-synth infrastructure ready!")
            print("   Install Claude Code for AI-powered design assistance")

    except Exception as e:
        print(f"❌ Setup failed: {e}")
        print("\nPlease report this issue at:")
        print("https://github.com/circuit-synth/circuit-synth/issues")
        sys.exit(1)


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser(
        description="Setup Claude Code integration for circuit-synth"
    )
    parser.add_argument(
        "--target-dir", type=Path, help="Target directory (default: current directory)"
    )

    args = parser.parse_args()
    main(args.target_dir)
