import os
from datetime import datetime

class GapDetector:
    def __init__(self, current_capabilities, desired_capabilities, impact_mapping=None):
        self.current_capabilities = current_capabilities
        self.desired_capabilities = desired_capabilities
        self.impact_mapping = impact_mapping or {
            "AI recommendations": 9,
            "real-time analytics": 8,
            "mobile app": 7,
            "user authentication": 5,
            "payment processing": 6
        }

    def detect_gaps(self):
        """Detect missing capabilities and rank by impact score."""
        missing = set(self.desired_capabilities) - set(self.current_capabilities)
        gaps = []
        for cap in missing:
            impact = self.impact_mapping.get(cap, 0)
            gaps.append((cap, impact))
        return sorted(gaps, key=lambda x: x[1], reverse=True)

    def generate_prd(self, critical_threshold=7):
        """Generate PRD content for gaps above critical threshold."""
        gaps = self.detect_gaps()
        critical_gaps = [cap for cap, impact in gaps if impact >= critical_threshold]
        
        if not critical_gaps:
            return "No critical gaps found for PRD generation."

        prd = f"# Product Requirements Document (PRD)\n\n## Date: {datetime.now().strftime('%Y-%m-%d')}\n\n"
        prd += "## Critical Gaps\n\n"
        for gap in critical_gaps:
            prd += f"- **{gap}**\n  - *Impact Score*: {self.impact_mapping[gap]}\n  - *Implementation Priority*: Critical\n  - *Requirements*: [To be defined]\n\n"
        return prd

    def run_daily_report(self, report_dir="reports"):
        """Execute full daily report workflow."""
        os.makedirs(report_dir, exist_ok=True)
        
        try:
            gaps = self.detect_gaps()
            
            # Generate gap report
            report_content = self._generate_report_content(gaps)
            report_path = os.path.join(report_dir, f"gap_report_{datetime.now().strftime('%Y%m%d')}.md")
            with open(report_path, 'w') as f:
                f.write(report_content)
            
            # Generate PRD for critical gaps
            prd_content = self.generate_prd()
            prd_path = os.path.join(report_dir, f"prd_critical_{datetime.now().strftime('%Y%m%d')}.md")
            with open(prd_path, 'w') as f:
                f.write(prd_content)
            
            return {
                "report_path": report_path,
                "prd_path": prd_path,
                "gaps_detected": len(gaps),
                "critical_gaps": len([cap for cap, imp in gaps if imp >= 7])
            }
        except Exception as e:
            raise RuntimeError(f"Daily report generation failed: {str(e)}") from e

    def _generate_report_content(self, gaps):
        """Format gap report content in Markdown."""
        content = "# Daily Gap Report\n\n"
        content += f"**Generated on**: {datetime.now().strftime('%Y-%m-%d')}\n\n"
        content += "## Missing Capabilities (Ranked by Impact)\n\n"
        content += "| Capability | Impact Score |\n"
        content += "|------------|--------------|\n"
        for cap, impact in gaps:
            content += f"| {cap} | {impact} |\n"
        content += "\n"
        return content

if __name__ == "__main__":
    # Example usage for demonstration
    current = ["user authentication", "payment processing"]
    desired = ["user authentication", "payment processing", "AI recommendations", "real-time analytics"]
    detector = GapDetector(current, desired)
    report = detector.run_daily_report()
    print(f"Daily report generated at: {report['report_path']}")
    print(f"PRD generated at: {report['prd_path']}")
    print(f"Found {report['gaps_detected']} gaps, {report['critical_gaps']} critical.")