#!/usr/bin/env python3
import csv
import os
import sys
import uuid
import xmlrpc.client

ODOO_URL = os.environ.get("ODOO_URL", "http://localhost:8069")
ODOO_DB = os.environ.get("ODOO_DB", "odoo")
ODOO_USER = os.environ.get("ODOO_USER", "products_api")
ODOO_PASSWORD = os.environ.get("ODOO_PASSWORD", "products_api_pass")

NAMESPACE_UUID = uuid.UUID("6ba7b810-9dad-11d1-80b4-00c04fd430c8")


def stable_uuid(kind: str, code: str) -> str:
    return str(uuid.uuid5(NAMESPACE_UUID, f"{kind}:{code}"))


def main(csv_path: str) -> None:
    if not os.path.exists(csv_path):
        raise SystemExit(f"CSV not found: {csv_path}")

    common = xmlrpc.client.ServerProxy(f"{ODOO_URL}/xmlrpc/2/common")
    uid = common.authenticate(ODOO_DB, ODOO_USER, ODOO_PASSWORD, {})
    if not uid:
        raise SystemExit("Odoo auth failed")
    models = xmlrpc.client.ServerProxy(f"{ODOO_URL}/xmlrpc/2/object")

    rows = []
    with open(csv_path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        fields = set(reader.fieldnames or [])
        use_comtrade = {"id", "text", "aggrLevel"}.issubset(fields)
        for r in reader:
            if use_comtrade:
                code = (r.get("id") or "").strip()
                name = (r.get("text") or "").strip()
                level = (r.get("aggrLevel") or "").strip()
            else:
                code = (r.get("code") or "").strip()
                name = (r.get("name") or "").strip()
                level = (r.get("level") or "").strip()

            if not code or not name or not level:
                continue
            if code.upper() == "TOTAL":
                continue
            if level not in {"2", "4", "6"}:
                continue
            rows.append((code, name, int(level)))

    rows.sort(key=lambda x: (x[2], x[0]))

    hs2_map = {}
    hs4_map = {}

    for code, name, level in rows:
        if level != 2:
            continue
        vals = {
            "uuid": stable_uuid("hs_category", code),
            "name": name,
            "hs_code": code,
            "level": 2,
            "parent_id": False,
        }
        cid = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, "products.category", "create", [vals])
        hs2_map[code] = cid

    for code, name, level in rows:
        if level != 4:
            continue
        parent_code = code[:2]
        parent_id = hs2_map.get(parent_code)
        if not parent_id:
            continue
        vals = {
            "uuid": stable_uuid("hs_category", code),
            "name": name,
            "hs_code": code,
            "level": 4,
            "parent_id": parent_id,
        }
        cid = models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, "products.category", "create", [vals])
        hs4_map[code] = cid

    product_count = 0
    skipped = 0
    for code, name, level in rows:
        if level != 6:
            continue
        parent_code = code[:4]
        parent_id = hs4_map.get(parent_code)
        if not parent_id:
            skipped += 1
            continue
        vals = {
            "uuid": stable_uuid("hs_product", code),
            "name": name,
            "hs_code": code,
            "category_id": parent_id,
        }
        models.execute_kw(ODOO_DB, uid, ODOO_PASSWORD, "products.product", "create", [vals])
        product_count += 1

    print(f"HS import complete: categories={len(hs2_map)+len(hs4_map)}, products={product_count}, skipped_products={skipped}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        raise SystemExit("Usage: import_hs_to_odoo_simple.py /path/to/hs_comtrade_reference.csv")
    main(sys.argv[1])
