#!/usr/bin/env python3
"""
Importa solo el stock positivo del respaldo Punto Zero (datos1.productos.Existencia)
al tenant de La Casita.  Usa part_number como llave de cruce.

Requiere pymysql y psycopg2. Instalar con:
    pip3 install --target /tmp/pylibs pymysql psycopg2-binary
"""
import os
import sys

sys.path.insert(0, "/tmp/pylibs")

import pymysql
import psycopg2

MYSQL_HOST = os.getenv("MYSQL_HOST", "127.0.0.1")
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3307"))
MYSQL_DB = os.getenv("MYSQL_DB", "datos1")
MYSQL_USER = os.getenv("MYSQL_USER", "root")
MYSQL_PASS = os.getenv("MYSQL_PASS", "")

PG_URL = os.getenv(
    "TENANT_DB_URL",
    "postgresql://postgres@localhost/tenant_refaccionaria_la_casita",
)
BRANCH_ID = int(os.getenv("BRANCH_ID", "1"))


def main():
    mysql = pymysql.connect(
        host=MYSQL_HOST,
        port=MYSQL_PORT,
        user=MYSQL_USER,
        password=MYSQL_PASS,
        db=MYSQL_DB,
        charset="latin1",
    )
    pg = psycopg2.connect(PG_URL)

    mycur = mysql.cursor()
    mycur.execute("SELECT Clave, Existencia FROM productos WHERE Existencia > 0")
    rows = mycur.fetchall()

    pgcur = pg.cursor()
    inserted = 0
    updated = 0
    skipped = 0
    for clave, existencia in rows:
        sku = str(clave).strip() if clave else ""
        if not sku:
            skipped += 1
            continue
        stock = int(round(float(existencia)))
        if stock <= 0:
            continue

        # Buscar inventory_id por part_number
        pgcur.execute(
            "SELECT id FROM inventory WHERE part_number = %s LIMIT 1",
            (sku,),
        )
        inv_row = pgcur.fetchone()
        if not inv_row:
            skipped += 1
            continue
        inventory_id = inv_row[0]

        pgcur.execute(
            """
            INSERT INTO inventory_stock (inventory_id, branch_id, stock, location)
            VALUES (%s, %s, %s, NULL)
            ON CONFLICT (inventory_id, branch_id) DO UPDATE
              SET stock = EXCLUDED.stock,
                  updated_at = NOW()
            """,
            (inventory_id, BRANCH_ID, stock),
        )
        if pgcur.rowcount == 1:
            # psycopg2 rowcount for INSERT ... ON CONFLICT is tricky
            inserted += 1
        else:
            updated += 1

    pg.commit()
    pgcur.close()
    mycur.close()
    mysql.close()
    pg.close()

    print(f"Productos con stock en respaldo: {len(rows)}")
    print(f"Filas insertadas/actualizadas en inventory_stock: {inserted + updated}")
    print(f"Sin coincidencia de part_number o SKU vacío: {skipped}")


if __name__ == "__main__":
    main()
