#!/usr/bin/env python3
"""
Smart Context Injection Hook
Injects relevant project context based on codebase type and current state
"""
import subprocess
import json
import sys
import os
import glob

def run_command(cmd):
    """Run shell command and return output"""
    try:
        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
        return result.stdout.strip(), result.stderr.strip(), result.returncode
    except Exception as e:
        return "", str(e), 1

def detect_project_type():
    """Detect project type based on files present"""
    project_types = []
    
    # Node.js/JavaScript
    if os.path.exists("package.json"):
        project_types.append("nodejs")
        
        # Check for specific frameworks
        with open("package.json", "r") as f:
            content = f.read()
            if "react" in content.lower():
                project_types.append("react")
            if "vue" in content.lower():
                project_types.append("vue")
            if "svelte" in content.lower():
                project_types.append("svelte")
            if "next" in content.lower():
                project_types.append("nextjs")
            if "express" in content.lower():
                project_types.append("express")
    
    # Python
    if os.path.exists("requirements.txt") or os.path.exists("pyproject.toml") or os.path.exists("setup.py"):
        project_types.append("python")
        
        if os.path.exists("manage.py"):
            project_types.append("django")
        if any(os.path.exists(f) for f in ["app.py", "main.py"]) and os.path.exists("requirements.txt"):
            with open("requirements.txt", "r") as f:
                content = f.read()
                if "flask" in content.lower():
                    project_types.append("flask")
                if "fastapi" in content.lower():
                    project_types.append("fastapi")
    
    # Go
    if os.path.exists("go.mod"):
        project_types.append("go")
    
    # Rust
    if os.path.exists("Cargo.toml"):
        project_types.append("rust")
    
    # Docker
    if os.path.exists("Dockerfile") or os.path.exists("docker-compose.yml"):
        project_types.append("docker")
    
    # Terraform
    if glob.glob("*.tf"):
        project_types.append("terraform")
    
    # Kubernetes
    if glob.glob("*.yaml") or glob.glob("*.yml"):
        yaml_files = glob.glob("*.yaml") + glob.glob("*.yml")
        for yaml_file in yaml_files:
            try:
                with open(yaml_file, "r") as f:
                    content = f.read()
                    if "apiVersion:" in content and "kind:" in content:
                        project_types.append("kubernetes")
                        break
            except:
                pass
    
    return project_types

def get_git_context():
    """Get current git context"""
    context = []
    
    # Current branch
    stdout, _, code = run_command("git branch --show-current")
    if code == 0 and stdout:
        context.append(f"Current branch: {stdout}")
    
    # Recent commits
    stdout, _, code = run_command("git log --oneline -5")
    if code == 0 and stdout:
        context.append("Recent commits:")
        for line in stdout.split('\n'):
            context.append(f"  {line}")
    
    # Uncommitted changes
    stdout, _, code = run_command("git status --porcelain")
    if code == 0 and stdout:
        changes = stdout.split('\n')
        context.append(f"Uncommitted changes: {len(changes)} files")
        # Show first few changed files
        for change in changes[:3]:
            context.append(f"  {change}")
        if len(changes) > 3:
            context.append(f"  ... and {len(changes) - 3} more")
    
    return context

def get_project_structure():
    """Get high-level project structure"""
    context = []
    
    # Key directories
    key_dirs = ["src", "lib", "components", "pages", "api", "routes", "models", "controllers", "services", "utils", "config", "tests", "__tests__", "spec"]
    existing_dirs = [d for d in key_dirs if os.path.isdir(d)]
    
    if existing_dirs:
        context.append(f"Key directories: {', '.join(existing_dirs)}")
    
    # Important files
    important_files = []
    file_patterns = [
        "README.md", "package.json", "requirements.txt", "go.mod", "Cargo.toml",
        "Dockerfile", "docker-compose.yml", "*.tf", "tsconfig.json", "webpack.config.js"
    ]
    
    for pattern in file_patterns:
        if "*" in pattern:
            files = glob.glob(pattern)
            important_files.extend(files[:2])  # Limit to 2 files per pattern
        elif os.path.exists(pattern):
            important_files.append(pattern)
    
    if important_files:
        context.append(f"Config files: {', '.join(important_files[:5])}")
    
    return context

def get_nodejs_context():
    """Get Node.js specific context"""
    context = []
    
    if os.path.exists("package.json"):
        try:
            with open("package.json", "r") as f:
                import json
                pkg = json.load(f)
                
                # Scripts
                if "scripts" in pkg:
                    scripts = list(pkg["scripts"].keys())
                    context.append(f"Available scripts: {', '.join(scripts[:5])}")
                
                # Dependencies
                deps = []
                if "dependencies" in pkg:
                    deps.extend(list(pkg["dependencies"].keys())[:5])
                if "devDependencies" in pkg:
                    deps.extend(list(pkg["devDependencies"].keys())[:3])
                
                if deps:
                    context.append(f"Key dependencies: {', '.join(deps[:8])}")
                    
        except Exception:
            pass
    
    return context

def get_python_context():
    """Get Python specific context"""
    context = []
    
    # Virtual environment
    if os.environ.get("VIRTUAL_ENV"):
        venv_name = os.path.basename(os.environ["VIRTUAL_ENV"])
        context.append(f"Virtual env: {venv_name}")
    
    # Requirements
    if os.path.exists("requirements.txt"):
        try:
            with open("requirements.txt", "r") as f:
                lines = [line.strip().split("==")[0] for line in f.readlines() if line.strip() and not line.startswith("#")]
                if lines:
                    context.append(f"Python packages: {', '.join(lines[:8])}")
        except Exception:
            pass
    
    return context

def get_docker_context():
    """Get Docker specific context"""
    context = []
    
    # Running containers
    stdout, _, code = run_command("docker ps --format 'table {{.Names}}\t{{.Status}}' 2>/dev/null")
    if code == 0 and stdout:
        lines = stdout.strip().split('\n')[1:]  # Skip header
        if lines and lines[0]:
            container_names = [line.split('\t')[0] for line in lines if line.strip()]
            context.append(f"Running containers: {', '.join(container_names[:3])}")
    
    # Docker compose services
    if os.path.exists("docker-compose.yml"):
        stdout, _, code = run_command("docker-compose config --services 2>/dev/null")
        if code == 0 and stdout:
            services = stdout.split('\n')
            services = [s for s in services if s.strip()]
            if services:
                context.append(f"Docker services: {', '.join(services[:5])}")
    
    return context

def get_terraform_context():
    """Get Terraform specific context"""
    context = []
    
    # Terraform workspace
    stdout, _, code = run_command("terraform workspace show 2>/dev/null")
    if code == 0 and stdout:
        context.append(f"Terraform workspace: {stdout}")
    
    # Terraform files
    tf_files = glob.glob("*.tf")
    if tf_files:
        context.append(f"Terraform files: {', '.join([os.path.basename(f) for f in tf_files[:5]])}")
    
    return context

def get_recent_activity():
    """Get recent development activity"""
    context = []
    
    # Recently modified files
    stdout, _, code = run_command("find . -name '*.py' -o -name '*.js' -o -name '*.ts' -o -name '*.go' -o -name '*.rs' | head -10 | xargs ls -lt 2>/dev/null | head -5")
    if code == 0 and stdout:
        lines = stdout.strip().split('\n')
        recent_files = []
        for line in lines:
            parts = line.split()
            if len(parts) > 8:
                filename = parts[-1]
                if filename != "." and not filename.startswith("./"):
                    recent_files.append(os.path.basename(filename))
        
        if recent_files:
            context.append(f"Recently modified: {', '.join(recent_files[:3])}")
    
    return context

def generate_context_injection():
    """Generate smart context injection"""
    project_types = detect_project_type()
    
    if not project_types:
        return  # No specific project detected
    
    context_sections = []
    
    # Project type header
    context_sections.append(f"## Project Context ({', '.join(project_types)})")
    
    # Git context
    git_context = get_git_context()
    if git_context:
        context_sections.append("### Git Status")
        context_sections.extend(git_context)
    
    # Project structure
    structure_context = get_project_structure()
    if structure_context:
        context_sections.append("### Project Structure")
        context_sections.extend(structure_context)
    
    # Technology-specific context
    if "nodejs" in project_types:
        nodejs_context = get_nodejs_context()
        if nodejs_context:
            context_sections.append("### Node.js Context")
            context_sections.extend(nodejs_context)
    
    if "python" in project_types:
        python_context = get_python_context()
        if python_context:
            context_sections.append("### Python Context")
            context_sections.extend(python_context)
    
    if "docker" in project_types:
        docker_context = get_docker_context()
        if docker_context:
            context_sections.append("### Docker Context")
            context_sections.extend(docker_context)
    
    if "terraform" in project_types:
        terraform_context = get_terraform_context()
        if terraform_context:
            context_sections.append("### Terraform Context")
            context_sections.extend(terraform_context)
    
    # Recent activity
    activity_context = get_recent_activity()
    if activity_context:
        context_sections.append("### Recent Activity")
        context_sections.extend(activity_context)
    
    # Output context
    if context_sections:
        print("\n".join(context_sections))

def main():
    try:
        generate_context_injection()
    except Exception as e:
        print(f"❌ Context injection error: {e}")
        sys.exit(0)  # Don't block Claude

if __name__ == "__main__":
    main()