import datetime
from pathlib import Path

class ReportBuilder:
    def __init__(self, target_path: Path, raw_findings: dict, scoring_results: dict):
        self.target_path = target_path
        self.raw_findings = raw_findings
        self.scoring_results = scoring_results

    def build(self) -> dict:
        detailed_issues = []
        bandit_results = self.raw_findings.get("bandit", {}).get("results", [])
        
        for issue in bandit_results:
            # Map bandit fields to schema
            severity = issue.get("issue_severity", "LOW")
            confidence = issue.get("issue_confidence", "LOW")
            
            if severity == "HIGH" and confidence == "HIGH":
                mapped_severity = "CRITICAL"
            else:
                mapped_severity = severity

            detailed_issues.append({
                "file": issue.get("filename", ""),
                "line": issue.get("line_number", 0),
                "issue_type": issue.get("test_name", "unknown_issue"),
                "severity": mapped_severity,
                "description": issue.get("issue_text", "")
            })

        counts = self.scoring_results["counts"]

        final_report = {
            "metadata": {
                "project_path": str(self.target_path),
                "generated_at": datetime.datetime.now().isoformat(),
                "version": "1.0.0"
            },
            "scoring": {
                "vibe_to_value_score": self.scoring_results["vibe_to_value_score"],
                "risk_level": self.scoring_results["risk_level"],
                "breakdown": self.scoring_results["breakdown"]
            },
            "findings_overview": {
                "critical_count": counts["critical"],
                "high_count": counts["high"],
                "medium_count": counts["medium"],
                "low_count": counts["low"]
            },
            "detailed_findings": {
                "issues": detailed_issues
            }
        }
        
        return final_report
