#!/usr/bin/env python3
"""
Deployment Pipeline Hook
Auto-deploy when conditions are met: tests pass, on main branch, etc.
"""
import subprocess
import json
import sys
import os
from datetime import datetime

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 get_current_branch():
    """Get current git branch"""
    stdout, _, code = run_command("git branch --show-current")
    return stdout if code == 0 else None

def has_package_json():
    """Check if package.json exists"""
    return os.path.exists("package.json")

def has_dockerfile():
    """Check if Dockerfile exists"""
    return os.path.exists("Dockerfile")

def has_docker_compose():
    """Check if docker-compose.yml exists"""
    return os.path.exists("docker-compose.yml") or os.path.exists("docker-compose.yaml")

def run_tests():
    """Run tests based on project type"""
    if has_package_json():
        # Node.js project
        stdout, stderr, code = run_command("npm test 2>/dev/null || npm run test 2>/dev/null")
        return code == 0, stdout, stderr
    
    # Python project
    if os.path.exists("pytest.ini") or os.path.exists("pyproject.toml"):
        stdout, stderr, code = run_command("python -m pytest 2>/dev/null")
        return code == 0, stdout, stderr
    
    # Go project
    if os.path.exists("go.mod"):
        stdout, stderr, code = run_command("go test ./... 2>/dev/null")
        return code == 0, stdout, stderr
    
    # No tests found, assume OK
    return True, "No tests configured", ""

def build_and_deploy():
    """Build and deploy based on project configuration"""
    results = []
    
    # Docker build
    if has_dockerfile():
        print("🐳 Building Docker image...")
        app_name = os.path.basename(os.getcwd())
        stdout, stderr, code = run_command(f"docker build -t {app_name}:latest .")
        
        if code == 0:
            results.append("✅ Docker build successful")
            
            # Try to restart if docker-compose exists
            if has_docker_compose():
                stdout, stderr, code = run_command("docker-compose up -d --no-deps")
                if code == 0:
                    results.append("✅ Service restarted via docker-compose")
                else:
                    results.append(f"⚠️ Docker-compose restart failed: {stderr}")
        else:
            results.append(f"❌ Docker build failed: {stderr}")
            return False, results
    
    # Node.js build
    elif has_package_json():
        print("📦 Building Node.js project...")
        stdout, stderr, code = run_command("npm run build 2>/dev/null")
        
        if code == 0:
            results.append("✅ Node.js build successful")
            
            # Try to restart PM2 process
            app_name = os.path.basename(os.getcwd())
            stdout, stderr, code = run_command(f"pm2 restart {app_name} 2>/dev/null")
            if code == 0:
                results.append("✅ PM2 process restarted")
        else:
            results.append(f"⚠️ Build failed: {stderr}")
    
    return True, results

def send_notification(message):
    """Send deployment notification"""
    # Try Telegram notification if configured
    if os.path.exists(os.path.expanduser("~/.kiro/hooks/telegram-alerts.py")):
        run_command(f'python ~/.kiro/hooks/telegram-alerts.py "🚀 {message}"')
    
    print(f"📢 {message}")

def should_deploy():
    """Check if we should deploy"""
    # Only deploy on main/master branch
    branch = get_current_branch()
    if branch not in ['main', 'master']:
        print(f"⏭️ Skipping deploy - not on main branch (current: {branch})")
        return False
    
    # Check if there are uncommitted changes
    stdout, _, code = run_command("git status --porcelain")
    if code == 0 and stdout.strip():
        print("⏭️ Skipping deploy - uncommitted changes detected")
        return False
    
    return True

def main():
    try:
        # Check if we're in a git repo
        stdout, _, code = run_command("git rev-parse --git-dir")
        if code != 0:
            sys.exit(0)  # Not a git repo, skip
        
        # Check deployment conditions
        if not should_deploy():
            sys.exit(0)
        
        print("🔍 Running pre-deployment checks...")
        
        # Run tests
        tests_passed, test_output, test_error = run_tests()
        
        if not tests_passed:
            print(f"❌ Tests failed - aborting deployment")
            print(f"Error: {test_error}")
            sys.exit(0)
        
        print("✅ All tests passed")
        
        # Build and deploy
        print("🚀 Starting deployment...")
        deploy_success, deploy_results = build_and_deploy()
        
        if deploy_success:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            app_name = os.path.basename(os.getcwd())
            
            # Log deployment
            with open(".deployment.log", "a") as f:
                f.write(f"{timestamp} - Deployment successful\n")
            
            # Send notification
            send_notification(f"Deployment successful: {app_name} @ {timestamp}")
            
            # Print results
            for result in deploy_results:
                print(result)
        else:
            print("❌ Deployment failed")
            for result in deploy_results:
                print(result)
            
    except Exception as e:
        print(f"❌ Deployment pipeline error: {e}")
        sys.exit(0)  # Don't block Claude

if __name__ == "__main__":
    main()