"""Report generation utilities."""

import json
import logging
from datetime import datetime
from pathlib import Path
from typing import List, Dict

from ..scanner.dependency_parser import Dependency
from ..scanner.confusion_checker import VulnerableDependency

logger = logging.getLogger(__name__)


class ReportWriter:
    """Generate scan reports."""
    
    def __init__(self, output_dir: Path):
        self.output_dir = output_dir
    
    def generate_all(
        self,
        target: str,
        dependencies: List[Dependency],
        vulnerabilities: List[VulnerableDependency],
        poc_paths: List[Path],
    ) -> None:
        """Generate all report formats."""
        self._generate_dependencies_json(dependencies)
        self._generate_report_json(target, dependencies, vulnerabilities, poc_paths)
        self._generate_report_markdown(target, dependencies, vulnerabilities, poc_paths)
        logger.info(f"Reports generated in {self.output_dir}")
    
    def _generate_dependencies_json(self, dependencies: List[Dependency]) -> None:
        """Generate dependencies.json."""
        data = [dep.to_dict() for dep in dependencies]
        output_file = self.output_dir / "dependencies.json"
        output_file.write_text(json.dumps(data, indent=2), encoding='utf-8')
        logger.info(f"Generated {output_file}")
    
    def _generate_report_json(
        self,
        target: str,
        dependencies: List[Dependency],
        vulnerabilities: List[VulnerableDependency],
        poc_paths: List[Path],
    ) -> None:
        """Generate report.json."""
        ecosystems = {}
        for dep in dependencies:
            ecosystems[dep.ecosystem] = ecosystems.get(dep.ecosystem, 0) + 1
        
        report = {
            "scan_date": datetime.now().isoformat(),
            "target": target,
            "summary": {
                "total_dependencies": len(dependencies),
                "vulnerable_dependencies": len(vulnerabilities),
                "generated_pocs": len(poc_paths),
                "ecosystems": ecosystems,
            },
            "vulnerabilities": [vuln.to_dict() for vuln in vulnerabilities],
            "poc_packages": [str(p) for p in poc_paths],
        }
        
        output_file = self.output_dir / "report.json"
        output_file.write_text(json.dumps(report, indent=2), encoding='utf-8')
        logger.info(f"Generated {output_file}")
    
    def _generate_report_markdown(
        self,
        target: str,
        dependencies: List[Dependency],
        vulnerabilities: List[VulnerableDependency],
        poc_paths: List[Path],
    ) -> None:
        """Generate report.md."""
        ecosystems = {}
        for dep in dependencies:
            ecosystems[dep.ecosystem] = ecosystems.get(dep.ecosystem, 0) + 1
        
        md = f"""# DepRaptor Scan Report

## Scan Information

- **Date**: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
- **Target**: {target}
- **Scanner**: DepRaptor v1.0.0
- **Developer**: LAKSHMIKANTHAN K (letchupkt)

## Summary

- **Total Dependencies**: {len(dependencies)}
- **Vulnerable Dependencies**: {len(vulnerabilities)}
- **Generated PoC Packages**: {len(poc_paths)}

## Ecosystem Breakdown

"""
        for ecosystem, count in ecosystems.items():
            md += f"- **{ecosystem}**: {count} packages\n"
        
        if vulnerabilities:
            md += "\n## Vulnerabilities Detected\n\n"
            for vuln in vulnerabilities:
                md += f"### {vuln.dependency.name}\n\n"
                md += f"- **Ecosystem**: {vuln.dependency.ecosystem}\n"
                md += f"- **Version**: {vuln.dependency.version}\n"
                md += f"- **Source**: {vuln.dependency.source}\n"
                md += f"- **Reason**: {vuln.reason}\n\n"
        else:
            md += "\n## No Vulnerabilities Detected\n\n"
            md += "All dependencies were found in public registries.\n"
        
        if poc_paths:
            md += "\n## Generated PoC Packages\n\n"
            for poc_path in poc_paths:
                md += f"- `{poc_path}`\n"
        
        md += "\n## Security Notice\n\n"
        md += "⚠️ **WARNING**: The PoC packages generated by this tool are intended ONLY for:\n\n"
        md += "- Authorized security testing\n- Bug bounty programs\n- Security research with proper authorization\n\n"
        md += "Do NOT upload these packages to public registries without authorization.\n"
        
        output_file = self.output_dir / "report.md"
        output_file.write_text(md, encoding='utf-8')
        logger.info(f"Generated {output_file}")
