import sys
from pathlib import Path
from pyshield.exporters import BaseExporter

class MarkdownExporter(BaseExporter):
    def export(self):
        
        lines = []
        lines.append("# PyShield Security Report\n")
        
        # Score
        lines.append("## Score\n")
        lines.append("| Metric | Value |")
        lines.append("|--------|-------|")
        lines.append(f"| Score | {self.report['scoring']['vibe_to_value_score']:.2f} |")
        lines.append(f"| Risk Level | {self.report['scoring']['risk_level']} |\n")
        
        # Risk Breakdown
        lines.append("## Risk Breakdown\n")
        breakdown = self.report["scoring"]["breakdown"]
        lines.append("| Component | Risk |")
        lines.append("|-----------|------|")
        lines.append(f"| SAST Risk Score | {breakdown['sast_risk_score']:.2f} |")
        lines.append(f"| Artifact Risk | {breakdown['artifact_risk']:.2f} |")
        lines.append(f"| Dependency Risk | {breakdown['dependency_risk']:.2f} |")
        lines.append(f"| Exploit Risk | {breakdown['exploit_risk']:.2f} |")
        lines.append(f"| Combined Risk | {breakdown['combined_risk']:.2f} |\n")
        
        # Findings Overview
        lines.append("## Findings Overview\n")
        counts = self.report["findings_overview"]
        lines.append("| Severity | Count |")
        lines.append("|----------|-------|")
        lines.append(f"| Critical | {counts['critical_count']} |")
        lines.append(f"| High | {counts['high_count']} |")
        lines.append(f"| Medium | {counts['medium_count']} |")
        lines.append(f"| Low | {counts['low_count']} |\n")
        
        # Detailed Findings
        lines.append("## Detailed Findings\n")
        issues = self.report["detailed_findings"]["issues"]
        if not issues:
            lines.append("No issues found. Excellent work!")
        else:
            lines.append("| Severity | File | Line | Issue |")
            lines.append("|----------|------|------|-------|")
            for issue in issues:
                lines.append(f"| {issue['severity']} | `{issue['file']}` | {issue['line']} | {issue['issue_type']}: {issue['description']} |")
        
        md_content = "\n".join(lines)
        
        if self.output_path:
            out_file = Path(self.output_path).resolve()
            out_file.write_text(md_content)
            print(f"Report saved to {out_file}", file=sys.stderr)
        else:
            print(md_content)
