import os
import platform
from loominar import __version__ as LOOMINAR_VERSION
from datetime import datetime
from collections import Counter
import matplotlib.pyplot as plt

SEVERITY_MAP = {
    "BLOCKER": "Blocker",
    "CRITICAL": "High",
    "MAJOR": "Medium",
    "MINOR": "Low",
    "INFO": "Info"
}

SEVERITY_COLORS = {
    "Blocker": "C00000",
    "High": "FF0000",
    "Medium": "FFC000",
    "Low": "92D050",
    "Info": "B4C6E7"
}


class BaseReport:
    def __init__(self, output_dir: str, project_key: str, fmt: str):
        self.output_dir = output_dir
        self.project_key = project_key
        self.format = fmt.lower().strip()
        os.makedirs(self.output_dir, exist_ok=True)
    
#----------------------------------
    def _build_filename(self, status=None):
        timestamp = datetime.now().strftime("%Y-%m-%d_%H%M")
        status_part = f"_{status.upper()}" if status else "_Report"
        return os.path.join(
            self.output_dir,
            f"{self.project_key}_Report_{timestamp}.{self.format}"
        )
    
#----------------------------------
    def _build_summary(self, issues):
        if not issues:
            return {"total": 0, "by_severity": {}, "by_type": {}}
        severities = [SEVERITY_MAP.get(i.get("severity", ""), i.get("severity", "")) for i in issues]
        types = [i.get("type", "") for i in issues]
        return {
            "total": len(issues),
            "by_severity": dict(Counter(severities)),
            "by_type": dict(Counter(types))
        }
    
#----------------------------------
    def generate_charts(self, summary):
        """Generate pie and bar charts for severity distribution."""
        if not summary["by_severity"]:
            return None, None

        labels = list(summary["by_severity"].keys())
        values = list(summary["by_severity"].values())
        colors = [f"#{SEVERITY_COLORS.get(l, '808080')}" for l in labels]

        pie_path = os.path.join(self.output_dir, f"{self.project_key}_severity_pie.png")
        bar_path = os.path.join(self.output_dir, f"{self.project_key}_severity_bar.png")

        # Pie chart
        plt.figure(figsize=(5, 5))
        plt.pie(values, labels=labels, colors=colors, autopct="%1.1f%%", startangle=140)
        plt.title("Issue Distribution by Severity")
        plt.tight_layout()
        plt.savefig(pie_path)
        plt.close()

        # Bar chart
        plt.figure(figsize=(6, 4))
        plt.bar(labels, values, color=colors)
        plt.title("Issue Count by Severity")
        plt.ylabel("Count")
        plt.xlabel("Severity")
        plt.tight_layout()
        plt.savefig(bar_path)
        plt.close()

        return pie_path, bar_path
    
#----------------------------------
    def _get_metadata(self):
        """Generate a dictionary of report metadata."""
        return {
            "Tool": f"Loominar v{LOOMINAR_VERSION}",
            "Generated On": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "Host": platform.node(),
            "System": f"{platform.system()} {platform.release()}",
            "Project": self.project_key
        }
    
#----------------------------------
    def _render_footer(self):
        """Return formatted footer string."""
        meta = self._get_metadata()
        return (
            f"\n\n──────────────────────────────────────────────\n"
            f"Generated by {meta['Tool']}\n"
            f"Project: {meta['Project']}\n"
            f"Generated On: {meta['Generated On']}\n"
            f"Host: {meta['Host']} ({meta['System']})\n"
            f"──────────────────────────────────────────────"
        )


# loominar/report/base_report.py
# Contains shared constants, color palette, filename logic, and the summary builder