"""FINXARIA · Demo FP&A (datos sintéticos, no clientes).
Ejecutar: python3 fpa_forecast.py --growth 5
Exporta fpa_simulado.csv. No requiere paquetes externos.
"""
import argparse
import csv
from pathlib import Path

MONTHS = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic']
PLAN = [78, 83, 86, 91, 95, 99, 104, 110, 108, 115, 121, 128]


def simulate(growth_pct: float):
    rows = []
    for i, (month, plan) in enumerate(zip(MONTHS, PLAN)):
        revenue = plan * (1 + growth_pct / 100) * (1 + ((i % 4) - 1.5) * .009)
        cogs = revenue * (.69 + (i % 3) * .008)
        opex = 95 / 12
        rows.append({'mes': month, 'presupuesto': round(plan, 2),
                     'ingresos': round(revenue, 2), 'costos_venta': round(cogs, 2),
                     'opex': round(opex, 2), 'ebitda': round(revenue-cogs-opex, 2)})
    return rows


if __name__ == '__main__':
    p = argparse.ArgumentParser()
    p.add_argument('--growth', type=float, default=5, help='Variación de ventas en porcentaje (-15 a 25)')
    args = p.parse_args()
    if not -15 <= args.growth <= 25: p.error('growth debe estar entre -15 y 25')
    rows = simulate(args.growth)
    dest = Path(__file__).with_name('fpa_simulado.csv')
    with dest.open('w', newline='', encoding='utf-8') as fh:
        writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
        writer.writeheader();writer.writerows(rows)
    totals = {k:sum(r[k] for r in rows) for k in ('ingresos', 'costos_venta', 'opex', 'ebitda')}
    print('DEMO · CLP millones · datos ficticios')
    print('Ingresos: %.1f | COGS: %.1f | OPEX: %.1f | EBITDA: %.1f | Margen: %.1f%%' %
          (totals['ingresos'],totals['costos_venta'],totals['opex'],totals['ebitda'],100*totals['ebitda']/totals['ingresos']))
    print('CSV:', dest)
