# -*- coding: utf-8 -*-
"""Build HTML: Đối chiếu Mua hàng T7 <-> Sản xuất T31 — Kg/cont quy đổi tháng (cont×4)"""
import json

SRC = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\BAOCAOTONGHOP\mua_sx_doichieu_T31.json"
OUT = r"C:\antigra-DS\CLAW_LAM_VIEC\Bao cao - Hanh chinh\BAOCAOTONGHOP\HTML\Bao_cao_DoiChieu_MuaHang_SanXuat_T7.html"

rows = json.load(open(SRC, encoding="utf-8"))
for r in rows:
    r['tb6'] = round(r['t6'] / 30) if r['t6'] else 0
    r['tb7'] = round(r['t7'] / 31)
    r['diff'] = r['tb7'] - r['tb6']
    r['pct'] = round(r['diff'] / r['tb6'] * 100, 1) if r['tb6'] else None
    r['cont_t'] = round(r['cont'] * 4)              # cont quy đổi tháng (~4 tuần)
    r['kg_cont'] = round(r['t7'] / r['cont_t']) if r['cont'] > 0 else None
    r['nm_show'] = r['nm'].replace('\n', ' / ')

TOT_KG = sum(r['t7'] for r in rows)
TOT_CONT = sum(r['cont'] for r in rows)
TOT_CONT_T = sum(r['cont_t'] for r in rows)
TOT_TB = round(TOT_KG / 31)
N = len(rows)
PCT = round(TOT_KG / 934548 * 100)
data_js = json.dumps(rows, ensure_ascii=False)

TPL = open(r"doichieu_template.html", encoding="utf-8").read()
html = (TPL
        .replace("@@N@@", str(N))
        .replace("@@PCT@@", str(PCT))
        .replace("@@TOT_TB@@", f"{TOT_TB:,}")
        .replace("@@TOT_CONT@@", str(TOT_CONT).replace('.', ','))
        .replace("@@TOT_CONT_T@@", str(TOT_CONT_T).replace('.', ','))
        .replace("@@DATA@@", data_js))
open(OUT, "w", encoding="utf-8").write(html)
print("SAVED:", OUT, "|", len(html), "chars")
print("Cont T31:", TOT_CONT, "-> quy doi thang:", TOT_CONT_T, "| KG:", TOT_KG)
print("Vi du kg_cont (Minh Hanh):", rows[0]['nm_show'], rows[0]['kg_cont'], "kg/cont/thang")
