#!/usr/bin/env python3
"""Fix Issue.customer via legacy ticket.account_id → Customer.legacy_account_id."""
import pymysql
import psycopg2

LEGACY = {"host": "legacy-db", "user": "facturation", "password": "***LEGACY-DB-PW-REDACTED***",
          "database": "gestionclient", "connect_timeout": 30, "read_timeout": 300}
PG = {"host": "db", "port": 5432, "user": "postgres", "password": "123",
      "dbname": "_eb65bdc0c4b1b2d6"}

def log(msg):
    print(msg, flush=True)

def main():
    log("=== Fix Issue → Customer via legacy_account_id ===")

    # Get ticket → account_id mapping
    mc = pymysql.connect(**LEGACY)
    cur = mc.cursor(pymysql.cursors.DictCursor)
    cur.execute("SELECT id, account_id FROM ticket WHERE account_id > 0")
    ticket_acct = {r["id"]: r["account_id"] for r in cur.fetchall()}
    mc.close()
    log("  {} tickets with account_id".format(len(ticket_acct)))

    pg = psycopg2.connect(**PG)
    pgc = pg.cursor()

    # Customer lookup
    pgc.execute('SELECT legacy_account_id, name, customer_name FROM "tabCustomer" WHERE legacy_account_id > 0')
    cust_map = {r[0]: (r[1], r[2]) for r in pgc.fetchall()}

    # Issues needing fix
    pgc.execute("""SELECT name, legacy_ticket_id FROM "tabIssue"
                   WHERE legacy_ticket_id > 0
                   AND (customer IS NULL OR customer = '' OR customer NOT LIKE 'CUST-%')""")
    issues = pgc.fetchall()
    log("  {} issues to fix".format(len(issues)))

    updated = 0
    for i, (issue_name, legacy_tid) in enumerate(issues):
        acct_id = ticket_acct.get(legacy_tid)
        if not acct_id:
            continue
        cust_data = cust_map.get(acct_id)
        if not cust_data:
            continue

        cust_name, cust_display = cust_data
        pgc.execute('UPDATE "tabIssue" SET customer = %s, customer_name = %s WHERE name = %s',
                     (cust_name, cust_display, issue_name))
        updated += 1

        if updated % 5000 == 0:
            pg.commit()
            log("  updated={}".format(updated))

    pg.commit()
    pg.close()
    log("\nIssues linked to Customer: {}".format(updated))

if __name__ == "__main__":
    main()
