# ================================================================
# services/inventory/app/schemas/sustainability.py
# ================================================================
"""
Sustainability Schemas - Environmental Impact & SDG Compliance
"""

from datetime import datetime
from typing import Dict, Any, List, Optional
from decimal import Decimal
from pydantic import BaseModel, Field


class PeriodInfo(BaseModel):
    """Time period for metrics"""
    start_date: str
    end_date: str
    days: int


class WasteMetrics(BaseModel):
    """Waste tracking metrics"""
    total_waste_kg: float = Field(description="Total waste in kilograms")
    production_waste_kg: float = Field(description="Waste from production processes")
    expired_waste_kg: float = Field(description="Waste from expired inventory")
    waste_percentage: float = Field(description="Waste as percentage of total production")
    waste_by_reason: Dict[str, float] = Field(description="Breakdown by waste reason")


class CO2Emissions(BaseModel):
    """CO2 emission metrics"""
    kg: float = Field(description="CO2 emissions in kilograms")
    tons: float = Field(description="CO2 emissions in tons")
    trees_to_offset: float = Field(description="Equivalent trees needed to offset emissions")


class WaterFootprint(BaseModel):
    """Water usage metrics"""
    liters: float = Field(description="Water footprint in liters")
    cubic_meters: float = Field(description="Water footprint in cubic meters")


class LandUse(BaseModel):
    """Land use metrics"""
    square_meters: float = Field(description="Land use in square meters")
    hectares: float = Field(description="Land use in hectares")


class HumanEquivalents(BaseModel):
    """Human-relatable equivalents for impact"""
    car_km_equivalent: float = Field(description="Equivalent kilometers driven by car")
    smartphone_charges: float = Field(description="Equivalent smartphone charges")
    showers_equivalent: float = Field(description="Equivalent showers taken")
    trees_planted: float = Field(description="Equivalent trees planted")


class EnvironmentalImpact(BaseModel):
    """Environmental impact of food waste"""
    co2_emissions: CO2Emissions
    water_footprint: WaterFootprint
    land_use: LandUse
    human_equivalents: HumanEquivalents


class SDG123Metrics(BaseModel):
    """UN SDG 12.3 specific metrics"""
    baseline_waste_percentage: float = Field(description="Baseline waste percentage")
    current_waste_percentage: float = Field(description="Current waste percentage")
    reduction_achieved: float = Field(description="Reduction achieved from baseline (%)")
    target_reduction: float = Field(description="Target reduction (50%)", default=50.0)
    progress_to_target: float = Field(description="Progress toward target (%)")
    status: str = Field(description="Status code: sdg_compliant, on_track, progressing, baseline")
    status_label: str = Field(description="Human-readable status")
    target_waste_percentage: float = Field(description="Target waste percentage to achieve")


class SDGCompliance(BaseModel):
    """SDG compliance assessment"""
    sdg_12_3: SDG123Metrics
    baseline_period: str = Field(description="Period used for baseline calculation")
    certification_ready: bool = Field(description="Ready for SDG certification")
    improvement_areas: List[str] = Field(description="Identified areas for improvement")


class EnvironmentalImpactAvoided(BaseModel):
    """Environmental impact avoided through AI"""
    co2_kg: float = Field(description="CO2 emissions avoided (kg)")
    water_liters: float = Field(description="Water saved (liters)")


class AvoidedWaste(BaseModel):
    """Waste avoided through AI predictions"""
    waste_avoided_kg: float = Field(description="Waste avoided in kilograms")
    ai_assisted_batches: int = Field(description="Number of AI-assisted batches")
    environmental_impact_avoided: EnvironmentalImpactAvoided
    methodology: str = Field(description="Calculation methodology")


class FinancialImpact(BaseModel):
    """Financial impact of waste"""
    waste_cost_eur: float = Field(description="Cost of waste in euros")
    cost_per_kg: float = Field(description="Average cost per kg")
    potential_monthly_savings: float = Field(description="Potential monthly savings")
    annual_projection: float = Field(description="Annual cost projection")


class GrantProgramEligibility(BaseModel):
    """Eligibility for a specific grant program"""
    eligible: bool = Field(description="Whether eligible for this grant")
    confidence: str = Field(description="Confidence level: high, medium, low")
    requirements_met: bool = Field(description="Whether requirements are met")
    funding_eur: float = Field(description="Available funding in euros")
    deadline: str = Field(description="Application deadline")
    program_type: str = Field(description="Type: grant, loan, or certification")
    sector_specific: Optional[str] = Field(None, description="Sector if specific: bakery, retail, etc.")


class SpainCompliance(BaseModel):
    """Spain-specific legal compliance"""
    law_1_2025: bool = Field(description="Compliance with Spanish Law 1/2025 on food waste")
    circular_economy_strategy: bool = Field(description="Aligned with Spanish Circular Economy Strategy")


class GrantReadiness(BaseModel):
    """Grant application readiness assessment"""
    overall_readiness_percentage: float = Field(description="Overall readiness percentage")
    grant_programs: Dict[str, GrantProgramEligibility] = Field(description="Eligibility by program")
    recommended_applications: List[str] = Field(description="Recommended grant programs to apply for")
    spain_compliance: SpainCompliance = Field(description="Spain-specific compliance status")


class SustainabilityMetrics(BaseModel):
    """Complete sustainability metrics response"""
    period: PeriodInfo
    waste_metrics: WasteMetrics
    environmental_impact: EnvironmentalImpact
    sdg_compliance: SDGCompliance
    avoided_waste: AvoidedWaste
    financial_impact: FinancialImpact
    grant_readiness: GrantReadiness


class BaselineComparison(BaseModel):
    """Baseline comparison for grants"""
    baseline: float
    current: float
    improvement: float


class SupportingData(BaseModel):
    """Supporting data for grant applications"""
    baseline_comparison: BaselineComparison
    environmental_benefits: EnvironmentalImpact
    financial_benefits: FinancialImpact


class Certifications(BaseModel):
    """Certification status"""
    sdg_12_3_compliant: bool
    grant_programs_eligible: List[str]


class ExecutiveSummary(BaseModel):
    """Executive summary for grant reports"""
    total_waste_reduced_kg: float
    waste_reduction_percentage: float
    co2_emissions_avoided_kg: float
    financial_savings_eur: float
    sdg_compliance_status: str


class ReportMetadata(BaseModel):
    """Report metadata"""
    generated_at: str
    report_type: str
    period: PeriodInfo
    tenant_id: str


class GrantReport(BaseModel):
    """Complete grant application report"""
    report_metadata: ReportMetadata
    executive_summary: ExecutiveSummary
    detailed_metrics: SustainabilityMetrics
    certifications: Certifications
    supporting_data: SupportingData


# Request schemas

class SustainabilityMetricsRequest(BaseModel):
    """Request for sustainability metrics"""
    start_date: Optional[datetime] = Field(None, description="Start date for metrics")
    end_date: Optional[datetime] = Field(None, description="End date for metrics")


class GrantReportRequest(BaseModel):
    """Request for grant report export"""
    grant_type: str = Field("general", description="Type of grant: general, eu_horizon, farm_to_fork, etc.")
    start_date: Optional[datetime] = Field(None, description="Start date for report")
    end_date: Optional[datetime] = Field(None, description="End date for report")
    format: str = Field("json", description="Export format: json, pdf, csv")


# Widget/Dashboard schemas

class SustainabilityWidgetData(BaseModel):
    """Simplified data for dashboard widgets"""
    total_waste_kg: float
    waste_reduction_percentage: float
    co2_saved_kg: float
    water_saved_liters: float
    trees_equivalent: float
    sdg_status: str
    sdg_progress: float
    grant_programs_ready: int
    financial_savings_eur: float
