"""
Report formatting and saving
"""
import json
from pathlib import Path
from datetime import datetime
from typing import Dict


def format_report(analysis_results: Dict, project_path: Path) -> Dict:
    """
    Format analysis results into a report
    
    Args:
        analysis_results: Results from scanner
        project_path: Project root path
        
    Returns:
        Formatted report dict with all features
    """
    return {
        "version": "2.0.0",
        "generated_at": datetime.utcnow().isoformat() + "Z",
        "project": {
            "path": str(project_path),
            "name": project_path.name
        },
        "summary": analysis_results["summary"],
        "endpoints": analysis_results["endpoints"],
        "api_calls": analysis_results["api_calls"],
        "connections": analysis_results["connections"],
        "blast_radius": analysis_results.get("blast_radius", []),
        "high_impact_nodes": analysis_results.get("high_impact_nodes", []),
        "accuracy": analysis_results.get("accuracy", {}),
        "metadata": {
            "files_scanned": analysis_results["files_scanned"]
        }
    }


def save_report(report: Dict, project_path: Path) -> Path:
    """
    Save report to .rohkun/reports/ directory
    
    Args:
        report: Report dict
        project_path: Project root path
        
    Returns:
        Path to saved report file
    """
    # Create reports directory
    reports_dir = project_path / ".rohkun" / "reports"
    reports_dir.mkdir(parents=True, exist_ok=True)
    
    # Generate filename with timestamp
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    report_file = reports_dir / f"report_{timestamp}.json"
    
    # Save report
    with open(report_file, 'w') as f:
        json.dump(report, f, indent=2)
    
    return report_file


def print_report_summary(report: Dict):
    """Print a human-readable summary of the report with all features"""
    summary = report["summary"]
    
    print("\n" + "="*60)
    print("ROHKUN ANALYSIS REPORT")
    print("="*60)
    print(f"\nProject: {report['project']['name']}")
    print(f"Generated: {report['generated_at']}")
    print(f"\nFiles Scanned: {report['metadata']['files_scanned']}")
    print(f"Endpoints Found: {summary['total_endpoints']}")
    print(f"API Calls Found: {summary['total_api_calls']}")
    print(f"Connections Found: {summary['total_connections']}")
    
    # Accuracy info
    accuracy = report.get('accuracy', {})
    if accuracy:
        print(f"\nEstimated Accuracy: {accuracy.get('estimated_accuracy', 'N/A')}")
        print(f"  High Confidence: {accuracy.get('high_confidence', 0)}")
        print(f"  Medium Confidence: {accuracy.get('medium_confidence', 0)}")
        print(f"  Low Confidence: {accuracy.get('low_confidence', 0)}")
    
    # High impact nodes
    high_impact = report.get('high_impact_nodes', [])
    if high_impact:
        print("\n" + "-"*60)
        print(f"HIGH IMPACT NODES ({len(high_impact)})")
        print("-"*60)
        print("These nodes have many dependents - changes would affect many files:")
        for node in high_impact[:5]:
            print(f"\n  {node['target']} ({node['severity'].upper()})")
            print(f"  {node['impact_description']}")
        if len(high_impact) > 5:
            print(f"\n  ... and {len(high_impact) - 5} more")
    
    # Connections with confidence
    if report['connections']:
        print("\n" + "-"*60)
        print("CONNECTIONS")
        print("-"*60)
        
        for i, conn in enumerate(report['connections'][:10], 1):  # Show first 10
            endpoint = conn['endpoint']
            api_call = conn['api_call']
            confidence = conn.get('confidence', 'unknown')
            confidence_score = conn.get('confidence_score', 0)
            
            # Color code by confidence
            conf_symbol = "●" if confidence == "high" else "◐" if confidence == "medium" else "○"
            
            confidence_desc = "very high" if confidence_score >= 90 else "high" if confidence_score >= 70 else "moderate" if confidence_score >= 50 else "low"
            print(f"\n{i}. {conf_symbol} {endpoint['method']} {endpoint['path']} ({confidence} confidence - {confidence_desc})")
            print(f"   Endpoint: {endpoint['file']}:{endpoint['line']}")
            print(f"   Called from: {api_call['file']}:{api_call['line']}")
            
            # Show confidence reasons if available
            reasons = conn.get('confidence_reasons', [])
            if reasons:
                print(f"   Reasons: {', '.join(reasons)}")
        
        if len(report['connections']) > 10:
            print(f"\n... and {len(report['connections']) - 10} more connections")
    
    # Blast radius summary
    blast_radius = report.get('blast_radius', [])
    if blast_radius:
        critical = sum(1 for b in blast_radius if b['severity'] == 'critical')
        high = sum(1 for b in blast_radius if b['severity'] == 'high')
        
        if critical or high:
            print("\n" + "-"*60)
            print("BLAST RADIUS SUMMARY")
            print("-"*60)
            if critical:
                print(f"  Critical Impact: {critical} nodes")
            if high:
                print(f"  High Impact: {high} nodes")
    
    print("\n" + "="*60 + "\n")
