import pandas as pd, numpy as np, json

df = pd.read_pickle("D:/Evolução categorias/.worktrees/comissao/analise_produtos.pkl")
df['FORNECEDOR'] = df['FORNECEDOR'].fillna('(SEM FORNECEDOR)').str.strip()

forn = df.groupby('FORNECEDOR').agg(
    TOT_PROD   =('REF_PROD','count'),
    PARADOS    =('REF_PROD', lambda x: ((df.loc[x.index,'QTD_VENDIDA']==0) & (df.loc[x.index,'ESTOQUE_ATUAL']>0)).sum()),
    VL_PARADO  =('VL_ESTOQUE', lambda x: x[df.loc[x.index,'QTD_VENDIDA']==0].sum()),
    VL_TOTAL   =('VL_ESTOQUE','sum'),
    RECEITA    =('VL_VENDIDO','sum'),
    LUCRO      =('LUCRO_BRUTO','sum'),
).reset_index()

forn['MARGEM'] = np.where(forn['RECEITA']>0, forn['LUCRO']/forn['RECEITA']*100, 0).round(1)
forn['PCT']    = np.where(forn['VL_TOTAL']>0, forn['VL_PARADO']/forn['VL_TOTAL']*100, 0).round(1)

# só fornecedores com alguma movimentação
forn = forn[(forn['VL_TOTAL']>0) | (forn['RECEITA']>0)].copy()
forn = forn.sort_values('VL_PARADO', ascending=False)

result = []
for _, r in forn.iterrows():
    result.append({
        "nome":     str(r.FORNECEDOR),
        "tot_prod": int(r.TOT_PROD),
        "parados":  int(r.PARADOS),
        "vl_parado":round(float(r.VL_PARADO),2),
        "vl_total": round(float(r.VL_TOTAL),2),
        "receita":  round(float(r.RECEITA),2),
        "lucro":    round(float(r.LUCRO),2),
        "margem":   round(float(r.MARGEM),1),
        "pct":      round(float(r.PCT),1),
    })

with open("D:/Evolução categorias/.worktrees/comissao/all_fornecedores.json","w",encoding="utf-8") as f:
    json.dump(result, f, ensure_ascii=False)

print(f"Total: {len(result)} fornecedores")
for r in result[:5]:
    print(f"  {r['nome'][:45]:45s} parado=R${r['vl_parado']:>10,.2f} pct={r['pct']}%")
