"""
Report generation utilities for carbon footprint analysis.
Produces structured reports with breakdowns, trends, and recommendations.
"""

from typing import List, Optional
from datetime import datetime
from .models import EmissionRecord, BusinessProfile, CarbonReport
from .calculator import CarbonCalculator


class ReportGenerator:
    """
    Generates comprehensive carbon footprint reports for businesses.
    Supports filtering by date range and custom report periods.
    """

    def __init__(self):
        """Initialize report generator with a calculator instance."""
        self._calculator = CarbonCalculator()

    def generate_report(
        self,
        business: BusinessProfile,
        records: List[EmissionRecord],
        period_start: str,
        period_end: str,
    ) -> CarbonReport:
        """
        Generate a full carbon footprint report for the given business and records.
        Records should already have co2_kg calculated.
        """
        # Filter records within the period
        filtered = self._filter_by_period(records, period_start, period_end)

        # Calculate totals and breakdowns
        total_kg = self._calculator.get_total_co2_kg(filtered)
        total_tonnes = self._calculator.get_total_co2_tonnes(filtered)
        by_category = self._calculator.get_breakdown_by_category(filtered)
        by_scope = self._calculator.get_breakdown_by_scope(filtered)
        recommendations = self._calculator.get_recommendations(filtered)

        return CarbonReport(
            business=business,
            records=filtered,
            total_co2_kg=total_kg,
            total_co2_tonnes=total_tonnes,
            breakdown_by_category=by_category,
            breakdown_by_scope=by_scope,
            period_start=period_start,
            period_end=period_end,
            recommendations=recommendations,
        )

    def generate_monthly_trend(
        self, records: List[EmissionRecord]
    ) -> dict:
        """
        Generate monthly emission trends from records.
        Returns dict with month keys and CO2 kg values.
        """
        monthly = {}
        for record in records:
            try:
                date = datetime.fromisoformat(record.date)
                key = date.strftime("%Y-%m")
            except (ValueError, TypeError):
                continue
            monthly[key] = monthly.get(key, 0) + record.co2_kg

        return {k: round(v, 4) for k, v in sorted(monthly.items())}

    def get_intensity_metrics(
        self, total_co2_kg: float, business: BusinessProfile
    ) -> dict:
        """
        Calculate emission intensity metrics per employee.
        Useful for benchmarking against industry averages.
        """
        if business.employee_count <= 0:
            return {"per_employee_kg": 0, "per_employee_tonnes": 0}

        per_employee = total_co2_kg / business.employee_count
        return {
            "per_employee_kg": round(per_employee, 2),
            "per_employee_tonnes": round(per_employee / 1000, 4),
        }

    def _filter_by_period(
        self, records: List[EmissionRecord], start: str, end: str
    ) -> List[EmissionRecord]:
        """Filter emission records by date range (inclusive)."""
        filtered = []
        for record in records:
            if start <= record.date <= end:
                filtered.append(record)
        return filtered
