"""
Agent orchestrator - coordinates the impact assessment workflow.
"""

from typing import List, Dict, Optional
from checkod.observe import get_diff
from checkod.understand import extract_symbols
from checkod.change_type import detect_change_type, format_change_summary
from checkod.assess import assess_risk, is_ollama_available
from checkod.summary import generate_impact_summary, classify_usage_by_category
from checkod.guard import should_warn_commit


def run_agent(
    repo_path: str = ".",
    enable_risk_assessment: bool = True,
    force_override: bool = False
) -> int:
    """
    Run the impact assessment agent.
    
    Args:
        repo_path: Path to the git repository to analyze
        enable_risk_assessment: Whether to use AI risk assessment (requires Ollama)
        force_override: Unused parameter for backward compatibility
        
    Returns:
        Exit code: 0 for success/advisory, 1 for error only
    """
    try:
        # Step 1: Observe - Get git diff
        diff_content = get_diff(repo_path)
        
        if not diff_content:
            print("ℹ️  No changes detected in the repository")
            return 0
        
        print(f"\n📋 Git Diff ({len(diff_content)} characters):")
        print("-" * 80)
        print(diff_content[:500] + "..." if len(diff_content) > 500 else diff_content)
        print("-" * 80)
        
        # Step 2: Understand - Extract changed symbols
        changed_symbols = extract_symbols(diff_content)
        
        # Step 3: Detect change types for each symbol
        change_types = detect_change_type(diff_content)
        
        # Step 4: Report - Display symbols with change types
        print(f"\n📊 Changed Symbols ({len(changed_symbols)} detected):")
        if changed_symbols:
            for symbol in changed_symbols:
                change_type = change_types.get(symbol, "unknown")
                print(f"  • {symbol} ({change_type})")
            
            # Print summary
            print(f"\n📈 Change Summary:")
            summary = format_change_summary(change_types)
            for line in summary.split("\n"):
                print(f"  {line}")
        else:
            print("  (No specific symbols detected - static parsing not implemented yet)")
        
        # Step 5: Assess Risk (optional, requires Ollama)
        highest_risk = "LOW"  # Track highest risk level
        if enable_risk_assessment and changed_symbols:
            print("\n" + "=" * 80)
            print("🤖 AI Risk Assessment (powered by local Ollama)")
            print("=" * 80)
            
            highest_risk = _run_risk_assessment(changed_symbols, change_types)
        
        # Step 6: Generate Impact Summary
        if changed_symbols:
            print("\n" + "=" * 80)
            print("📋 Impact Summary")
            print("=" * 80)
            
            _generate_summaries(changed_symbols, change_types)
        
        # Step 7: Guard - Advisory warning for HIGH risk changes
        if should_warn_commit(highest_risk):
            print("\n" + "=" * 80)
            print("⚠️  HIGH IMPACT CHANGE DETECTED")
            print("\nThis change may affect critical system behavior.")
            print("\nRecommended:")
            print("  • run related tests")
            print("  • verify downstream services")
            print("  • review impact summary")
            print("\nCommit will proceed.")
            print("=" * 80)
        
        return 0
        
    except Exception as e:
        print(f"❌ Error during assessment: {str(e)}")
        return 1
        return 1


def _run_risk_assessment(symbols: List[str], change_types: Dict[str, str]) -> str:
    """
    Run risk assessment for changed symbols.
    
    Args:
        symbols: List of changed symbol names
        change_types: Dict mapping symbols to change types
        
    Returns:
        Highest risk level found: "HIGH", "MEDIUM", or "LOW"
    """
    from checkod.assess import assess_risk, is_ollama_available, prompt_and_install_ollama_if_needed
    
    # Check if Ollama is available, offer installation if not
    if not is_ollama_available():
        if not prompt_and_install_ollama_if_needed():
            print("\n⚠️  Ollama not available. Skipping AI risk assessment.")
            print("    To enable later: ollama serve")
            return "LOW"
    
    print("\n📍 Analyzing risk for each symbol...\n")
    
    highest_risk = "LOW"  # Track highest risk level
    risk_hierarchy = {"HIGH": 3, "MEDIUM": 2, "LOW": 1}
    
    for symbol in symbols:
        try:
            # Get change type for context
            change_type = change_types.get(symbol, "unknown")
            
            # Build context about the change
            usage_locations = [f"[{change_type}]"]  # Add change type as context
            
            # In a real implementation, we would have symbol usage data
            # For now, use change type as context for the LLM
            risk_assessment = assess_risk(symbol, usage_locations)
            
            # Extract risk level from assessment (look for HIGH/MEDIUM/LOW)
            current_risk = "MEDIUM"  # Default
            if "HIGH" in risk_assessment.upper():
                current_risk = "HIGH"
            elif "LOW" in risk_assessment.upper():
                current_risk = "LOW"
            
            # Update highest risk
            if risk_hierarchy.get(current_risk, 0) > risk_hierarchy.get(highest_risk, 0):
                highest_risk = current_risk
            
            print(f"Symbol: {symbol}")
            print(f"Change: {change_type}")
            print("-" * 40)
            print(risk_assessment)
            print()
            
        except Exception as e:
            print(f"⚠️  Risk assessment failed for {symbol}: {str(e)}\n")
    
    return highest_risk


def _generate_summaries(symbols: List[str], change_types: Dict[str, str]) -> None:
    """
    Generate impact summaries for each changed symbol.
    
    Args:
        symbols: List of changed symbols
        change_types: Dict mapping symbols to change types
    """
    for symbol in symbols:
        try:
            change_type = change_types.get(symbol, "unknown")
            
            # Create mock usage classification for demonstration
            # In real implementation, would come from dependency analysis
            classified_usage = {
                "service": [f"{symbol.lower()}_service"],
                "api": [f"/api/{symbol.lower()}"],
                "test": [f"test_{symbol.lower()}"],
            }
            
            # Generate summary (risk level would come from assess_risk in production)
            summary = generate_impact_summary(
                symbol,
                change_type,
                classified_usage,
                risk_level="MEDIUM"  # Placeholder - would be from risk assessment
            )
            
            print(summary)
            print()
            
        except Exception as e:
            print(f"⚠️  Summary generation failed for {symbol}: {str(e)}\n")

