#!/usr/bin/env python3
from __future__ import annotations
import csv, json
from datetime import datetime, timezone
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1]
SOURCE=ROOT/'catalog-source.csv'
OUTPUT=ROOT/'data/products.json'
def boolean(v:str)->bool:return str(v).strip().lower() in {'1','true','yes','si','sí'}
def main()->int:
    products=[]
    with SOURCE.open(newline='',encoding='utf-8-sig') as handle:
        for row in csv.DictReader(handle):
            raw=(row.get('price') or '').strip()
            price=int(float(raw)) if raw else None
            products.append({
                'id':row['id'].strip(),'name':row['name'].strip(),
                'category':row['category'].strip(),'collection':row['collection'].strip(),
                'description':row['description'].strip(),'dimensions':row['dimensions'].strip(),
                'price':price,'priceText':'Consultar disponibilidad' if price is None else '',
                'available':boolean(row['available']),'featured':boolean(row['featured']),
                'new':boolean(row['new']),'stockText':'Disponible para confirmar',
                'images':[row['image'].strip()],
                'source':{'type':'instagram-export','account':'ari_shopping1','fbid':row['source_fbid'].strip()}
            })
    OUTPUT.write_text(json.dumps({'version':'2.1.0','updatedAt':datetime.now(timezone.utc).isoformat(),'currency':'COP','pricingMode':'consult','products':products},ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
    print(f'OK: {len(products)} productos escritos en {OUTPUT}')
    return 0
if __name__=='__main__':raise SystemExit(main())
