"""AI confidence analysis and reporting."""

from dataclasses import dataclass
from typing import List, Dict
from .scanner import ScanResult, IssueType


@dataclass
class ConfidenceReport:
    """Overall confidence report for a PR."""
    total_files: int
    scanned_files: int
    avg_ai_confidence: float
    high_risk_files: List[str]
    total_issues: int
    issues_by_type: Dict[str, int]
    overall_risk: str  # "low", "medium", "high"


class AIConfidenceAnalyzer:
    """Analyzes scan results and generates confidence reports."""
    
    def analyze(self, results: List[ScanResult]) -> ConfidenceReport:
        """Analyze scan results and generate a report."""
        if not results:
            return ConfidenceReport(
                total_files=0,
                scanned_files=0,
                avg_ai_confidence=0.0,
                high_risk_files=[],
                total_issues=0,
                issues_by_type={},
                overall_risk="low"
            )
        
        # Calculate average AI confidence
        avg_confidence = sum(r.ai_confidence_score for r in results) / len(results)
        
        # Identify high-risk files (AI confidence > 0.7)
        high_risk = [r.file_path for r in results if r.ai_confidence_score > 0.7]
        
        # Count issues by type
        issues_by_type: Dict[str, int] = {}
        total_issues = 0
        
        for result in results:
            for issue in result.issues:
                issue_type = issue.type.value
                issues_by_type[issue_type] = issues_by_type.get(issue_type, 0) + 1
                total_issues += 1
        
        # Determine overall risk level
        overall_risk = self._calculate_overall_risk(avg_confidence, high_risk, total_issues)
        
        return ConfidenceReport(
            total_files=len(results),
            scanned_files=len(results),
            avg_ai_confidence=round(avg_confidence, 2),
            high_risk_files=high_risk,
            total_issues=total_issues,
            issues_by_type=issues_by_type,
            overall_risk=overall_risk
        )
    
    def _calculate_overall_risk(
        self, avg_confidence: float, high_risk_files: List[str], total_issues: int
    ) -> str:
        """Calculate overall risk level."""
        if avg_confidence > 0.7 or len(high_risk_files) > 2:
            return "high"
        elif avg_confidence > 0.4 or total_issues > 10:
            return "medium"
        else:
            return "low"
    
    def format_markdown(self, report: ConfidenceReport, results: List[ScanResult]) -> str:
        """Format report as markdown for GitHub comment."""
        risk_emoji = {
            "low": "✅",
            "medium": "⚠️",
            "high": "🚨"
        }
        
        md = f"""## 🛡️ PR Guardian Scan Results

**Overall Risk Level**: {risk_emoji[report.overall_risk]} {report.overall_risk.upper()}

### Summary
- **Files Scanned**: {report.scanned_files}
- **Average AI Confidence**: {report.avg_ai_confidence:.0%}
- **Total Issues Found**: {report.total_issues}
- **High-Risk Files**: {len(report.high_risk_files)}

"""
        
        if report.high_risk_files:
            md += "### ⚠️ High-Risk Files (AI Confidence > 70%)\n\n"
            for file_path in report.high_risk_files:
                result = next(r for r in results if r.file_path == file_path)
                md += f"- `{file_path}` - {result.ai_confidence_score:.0%} AI confidence\n"
            md += "\n"
        
        if report.issues_by_type:
            md += "### Issues by Type\n\n"
            for issue_type, count in sorted(report.issues_by_type.items(), key=lambda x: -x[1]):
                md += f"- **{issue_type.replace('_', ' ').title()}**: {count}\n"
            md += "\n"
        
        # Detailed file reports
        md += "### 📄 Detailed File Reports\n\n"
        
        for result in sorted(results, key=lambda r: -r.ai_confidence_score):
            confidence_bar = self._confidence_bar(result.ai_confidence_score)
            md += f"#### {result.file_path}\n"
            md += f"**AI Confidence**: {confidence_bar} {result.ai_confidence_score:.0%}\n"
            md += f"**Issues**: {len(result.issues)} ({result.error_count} errors, {result.warning_count} warnings)\n\n"
            
            if result.issues:
                for issue in result.issues[:5]:  # Show top 5 issues per file
                    severity_emoji = {"error": "❌", "warning": "⚠️", "info": "ℹ️"}
                    md += f"- {severity_emoji.get(issue.severity, '•')} Line {issue.line}: {issue.message}\n"
                
                if len(result.issues) > 5:
                    md += f"- ... and {len(result.issues) - 5} more\n"
                
                md += "\n"
        
        md += """---

<sub>🤖 Generated by [PR Guardian](https://github.com/prguardian/pr-guardian) - Protecting your code, one PR at a time</sub>
"""
        
        return md
    
    def _confidence_bar(self, confidence: float) -> str:
        """Generate a visual confidence bar."""
        filled = int(confidence * 10)
        empty = 10 - filled
        return f"[{'█' * filled}{'░' * empty}]"
