import json
from typing import Dict, List, Any
from datetime import datetime
import os

class ReportGenerator:
    def __init__(self):
        print("📄 Report generator ready")

    def generate_json_report(self, results: List[Dict[str, Any]], summary: Dict[str, Any] = None) -> str:
        """Generate a clean, human-readable JSON report"""
        print("🔄 Generating JSON report...")

        # Create simplified results for output
        simplified_results = []
        for result in results:
            simplified_result = {
                "approved": result.get("approved", False),
                "reason": result.get("reason", "Unknown"),
                "link": result.get("link", "Unknown"),
                "confidence": round(result.get("confidence", 0.0), 2),
                "text_found": bool(result.get("text_extracted", "").strip()),
                "word_count": result.get("word_count", 0)
            }

            # Add key guideline matches if available
            matches = result.get("guideline_matches", [])
            if matches:
                top_matches = sorted(matches, key=lambda x: x["confidence"], reverse=True)[:2]
                simplified_result["key_matches"] = [
                    {
                        "category": match["category"],
                        "type": match["type"],
                        "confidence": round(match["confidence"], 2)
                    }
                    for match in top_matches
                ]

            simplified_results.append(simplified_result)

        # Create final report structure
        report = {
            "evaluation_report": {
                "timestamp": datetime.now().isoformat(),
                "summary": summary or self._generate_basic_summary(simplified_results),
                "results": simplified_results
            }
        }

        print(f"   ✅ JSON report generated - {len(simplified_results)} results")
        return json.dumps(report, indent=2, ensure_ascii=False)

    def _generate_basic_summary(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
        total = len(results)
        approved = sum(1 for r in results if r["approved"])

        return {
            "total_images": total,
            "approved": approved,
            "rejected": total - approved,
            "approval_rate": round(approved / total if total > 0 else 0, 2)
        }

    def save_report(self, report_json: str, output_path: str = None) -> str:
        """Save the JSON report to a file"""
        if output_path is None:
            # Create reviews directory if it doesn't exist
            os.makedirs('reviews', exist_ok=True)
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = f"reviews/content_evaluation_report_{timestamp}.json"

        print(f"💾 Saving report to: {output_path}")
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(report_json)

        print(f"   ✅ Report saved successfully")
        return output_path

    def generate_detailed_report(self, results: List[Dict[str, Any]], summary: Dict[str, Any] = None) -> str:
        """Generate a more detailed JSON report with full analysis data"""
        print("🔄 Generating detailed JSON report...")

        report = {
            "detailed_evaluation_report": {
                "timestamp": datetime.now().isoformat(),
                "summary": summary or self._generate_detailed_summary(results),
                "evaluation_criteria": {
                    "text_quality_threshold": 30,
                    "image_quality_required": True,
                    "semantic_similarity_threshold": 0.4,
                    "rejection_threshold": 0.8
                },
                "results": results
            }
        }

        print(f"   ✅ Detailed JSON report generated - {len(results)} results")
        return json.dumps(report, indent=2, ensure_ascii=False)

    def _generate_detailed_summary(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
        total = len(results)
        approved = sum(1 for r in results if r.get("approved", False))

        # Analyze rejection reasons
        rejection_categories = {}
        confidence_scores = []

        for result in results:
            if result.get("confidence"):
                confidence_scores.append(result["confidence"])

            if not result.get("approved", False):
                reason = result.get("reason", "Unknown")
                if "text" in reason.lower() and "unclear" in reason.lower():
                    category = "Poor Text Quality"
                elif "quality" in reason.lower() and "poor" in reason.lower():
                    category = "Poor Image Quality"
                elif "guideline" in reason.lower():
                    category = "Brand Guidelines"
                else:
                    category = "Other"

                rejection_categories[category] = rejection_categories.get(category, 0) + 1

        avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else 0

        return {
            "total_images": total,
            "approved": approved,
            "rejected": total - approved,
            "approval_rate": round(approved / total if total > 0 else 0, 2),
            "average_confidence": round(avg_confidence, 2),
            "rejection_breakdown": rejection_categories
        }