"""Phaxor — Solar Sizing Engine (Python port)"""
import math

SEASON_FACTORS = [0.7, 0.8, 0.95, 1.0, 1.05, 1.1, 1.1, 1.05, 1.0, 0.9, 0.75, 0.65]
MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

def solve_solar_sizing(inputs: dict) -> dict | None:
    """Solar PV System Sizing Calculator."""
    load_kw = float(inputs.get('averageLoadKw', 0))
    usage_hours = float(inputs.get('usageHoursPerDay', 6))
    psh = float(inputs.get('peakSunHours', 5))
    sys_loss = float(inputs.get('systemLoss', 20))
    autonomy_days = float(inputs.get('autonomyDays', 1))
    batt_v = float(inputs.get('batteryVoltage', 48))
    dod = float(inputs.get('depthOfDischarge', 50))
    panel_watt = float(inputs.get('panelWattage', 400))
    panel_vmp = float(inputs.get('panelVmp', 41.2))

    if load_kw <= 0 or panel_watt <= 0:
        return None

    hrs = max(0, usage_hours)
    psh = max(0.1, psh)
    loss = (max(0, sys_loss) or 20) / 100.0
    auto = max(0, autonomy_days)
    b_v = max(12, batt_v)
    dod_val = (max(10, dod) or 50) / 100.0

    # 1. Daily Energy
    daily_energy = load_kw * hrs

    # 2. Required Generation
    required_gen = daily_energy / (1.0 - loss)

    # 3. Array Size
    array_size_kw = required_gen / psh

    # 4. Panels
    num_panels = math.ceil(array_size_kw * 1000.0 / panel_watt)
    actual_array_kw = num_panels * panel_watt / 1000.0

    # 5. Inverter
    inverter_kva = math.ceil(load_kw * 1.25 * 10.0) / 10.0

    # 6. Battery
    batt_wh = daily_energy * auto * 1000.0
    batt_ah = batt_wh / (b_v * dod_val) if batt_wh > 0 else 0
    
    batt_num = 1
    if b_v == 48:
        batt_num = 4
    elif b_v == 24:
        batt_num = 2
    
    # 7. Strings
    panels_per_string = math.ceil(b_v * 1.5 / panel_vmp)
    strings = math.ceil(num_panels / max(panels_per_string, 1))

    # 8. Monthly Data
    monthly_data = []
    annual_gen = 0
    for i in range(12):
        gen = actual_array_kw * psh * SEASON_FACTORS[i] * 30 * (1.0 - loss)
        demand = daily_energy * 30
        monthly_data.append({
            'month': MONTHS[i],
            'gen': int(round(gen)),
            'demand': int(round(demand))
        })
        annual_gen += gen

    annual_demand = daily_energy * 365

    return {
        'dailyEnergyKwh': float(f"{daily_energy:.2f}"),
        'requiredGenKwh': float(f"{required_gen:.2f}"),
        'arraySizeKw': float(f"{array_size_kw:.2f}"),
        'numPanels': int(num_panels),
        'actualArrayKw': float(f"{actual_array_kw:.2f}"),
        'inverterKva': float(f"{inverter_kva:.2f}"),
        'batteryAh': int(round(batt_ah)),
        'batterySeriesCount': int(batt_num),
        'panelsPerString': int(panels_per_string),
        'strings': int(strings),
        'monthlyGeneration': monthly_data,
        'annualGenKwh': int(round(annual_gen)),
        'annualDemandKwh': int(round(annual_demand))
    }
