"""
Project scanner - orchestrates the analysis
"""
from pathlib import Path
from typing import Dict, List
from ..utils.file_utils import scan_directory, read_file_safe
from .endpoints import find_endpoints
from .api_calls import find_api_calls
from .matcher import match_connections
from .confidence import calculate_connection_confidence, calculate_accuracy_boundaries
from .blast_radius import BlastRadiusCalculator


def scan_project(project_path: Path) -> Dict:
    """
    Scan project and analyze code
    
    Args:
        project_path: Root directory of project
        
    Returns:
        Dict with analysis results including blast radius and confidence scores
    """
    # Get all files to scan
    files = scan_directory(project_path)
    
    # Analyze files
    all_endpoints = []
    all_api_calls = []
    
    for file_path in files:
        content = read_file_safe(file_path)
        if not content:
            continue
        
        # Find endpoints in this file
        endpoints = find_endpoints(file_path, content)
        all_endpoints.extend(endpoints)
        
        # Find API calls in this file
        api_calls = find_api_calls(file_path, content)
        all_api_calls.extend(api_calls)
    
    # Match connections
    connections = match_connections(all_endpoints, all_api_calls)
    
    # Add confidence scores to connections
    for conn in connections:
        confidence_data = calculate_connection_confidence(conn['endpoint'], conn['api_call'])
        conn['confidence'] = confidence_data['confidence']
        conn['confidence_reasons'] = confidence_data['reasons']
    
    # Calculate confidence distribution
    confidence_dist = calculate_accuracy_boundaries(connections)
    
    # Build blast radius analysis
    blast_radius_calc = BlastRadiusCalculator()
    blast_radius_calc.build_from_analysis(all_endpoints, all_api_calls, connections)
    
    # Calculate blast radius for all endpoints
    blast_radius_results = []
    for endpoint in all_endpoints:
        identifier = f"{endpoint['method']}:{endpoint['path']}"
        result = blast_radius_calc.calculate_blast_radius(identifier)
        if result:
            blast_radius_results.append({
                "target": result.target,
                "target_type": result.target_type,
                "target_file": result.target_file,
                "target_line": result.target_line,
                "direct_dependents": result.direct_dependents,
                "total_dependents": result.total_dependents,
                "affected_files": list(result.affected_files),
                "affected_endpoints": list(result.affected_endpoints),
                "severity": result.severity,
                "impact_description": result.impact_description
            })
    
    # Find high-impact nodes
    high_impact = blast_radius_calc.get_high_impact_nodes(min_severity="high")
    
    return {
        "files_scanned": len(files),
        "endpoints": all_endpoints,
        "api_calls": all_api_calls,
        "connections": connections,
        "blast_radius": blast_radius_results,
        "high_impact_nodes": [
            {
                "target": r.target,
                "severity": r.severity,
                "total_dependents": r.total_dependents,
                "impact_description": r.impact_description
            }
            for r in high_impact[:10]  # Top 10
        ],
        "confidence_distribution": confidence_dist,
        "summary": {
            "total_endpoints": len(all_endpoints),
            "total_api_calls": len(all_api_calls),
            "total_connections": len(connections),
            "certain_connections": confidence_dist.get('certain', 0),
            "high_confidence_connections": confidence_dist.get('high', 0),
            "medium_confidence_connections": confidence_dist.get('medium', 0),
            "low_confidence_connections": confidence_dist.get('low', 0),
            "high_impact_nodes": len(high_impact)
        }
    }
