"""Explore legacy services + product descriptions for Expro Transit."""
import pymysql
conn = pymysql.connect(
    host="legacy-db", user="facturation",
    password="*******", database="gestionclient",
    cursorclass=pymysql.cursors.DictCursor
)

ACCOUNT_ID = 3673

with conn.cursor() as cur:
    # Get delivery IDs for this account
    cur.execute("SELECT id FROM delivery WHERE account_id = %s", (ACCOUNT_ID,))
    delivery_ids = [r["id"] for r in cur.fetchall()]
    print("Delivery IDs for account {}: {}".format(ACCOUNT_ID, delivery_ids))

    if not delivery_ids:
        print("No deliveries found!")
        exit()

    placeholders = ",".join(["%s"] * len(delivery_ids))

    # French product translations
    cur.execute("""
        SELECT pt.product_id, pt.name as pname, pt.description_short, p.sku, p.price
        FROM product_translate pt
        JOIN product p ON p.id = pt.product_id
        WHERE pt.language_id = 'fr'
        AND p.sku IN ('FTTB1000I','CSERV','FTTH_LOCMOD','FTT_HFAR','HVIPFIXE','RAB24M','TELEPMENS','RAB2X')
    """)
    print("\n=== French product names ===")
    for r in cur.fetchall():
        print("  sku={:<14} price={:>8} name={}".format(r["sku"], r["price"], r["pname"]))

    # All active services at these delivery addresses
    cur.execute("""
        SELECT s.id, s.delivery_id, s.product_id, s.hijack, s.hijack_price, s.hijack_desc,
               s.comment, s.radius_user, s.radius_pwd,
               p.sku, p.price as base_price, p.category, p.type,
               pt.name as prod_name, pt.description_short
        FROM service s
        JOIN product p ON p.id = s.product_id
        LEFT JOIN product_translate pt ON pt.product_id = p.id AND pt.language_id = 'fr'
        WHERE s.delivery_id IN ({}) AND s.status = 1
        ORDER BY s.delivery_id, p.category, p.sku
    """.format(placeholders), delivery_ids)
    services = cur.fetchall()

    print("\n=== Active services for Expro ({} total) ===".format(len(services)))
    current_delivery = None
    subtotal = 0
    grand_total = 0
    for s in services:
        if s["delivery_id"] != current_delivery:
            if current_delivery is not None:
                print("    {:>58} ──────".format(""))
                print("    {:>58} {:>8.2f}$".format("Sous-total:", subtotal))
                grand_total += subtotal
                subtotal = 0
            current_delivery = s["delivery_id"]
            print("\n  ── Delivery {} ──".format(s["delivery_id"]))

        price = s["hijack_price"] if s["hijack"] else s["base_price"]
        desc = s["hijack_desc"] if s["hijack"] and s["hijack_desc"] else s["prod_name"]
        subtotal += float(price or 0)

        is_rebate = float(price or 0) < 0
        indent = "    " if is_rebate else "  "
        print("  {}svc={:<6} sku={:<14} {:>8.2f}$ {} {}".format(
            indent, s["id"], s["sku"], float(price or 0),
            desc or "", "({})".format(s["comment"]) if s["comment"] else ""))
        if s["radius_user"]:
            print("  {}         PPPoE: {}".format(indent, s["radius_user"]))

    if current_delivery is not None:
        print("    {:>58} ──────".format(""))
        print("    {:>58} {:>8.2f}$".format("Sous-total:", subtotal))
        grand_total += subtotal

    print("\n  GRAND TOTAL: {:,.2f}$".format(grand_total))

    # Also get all product categories
    cur.execute("DESCRIBE product_cat")
    print("\n=== product_cat table ===")
    for r in cur.fetchall():
        print("  {} {}".format(r["Field"], r["Type"]))

    cur.execute("SELECT * FROM product_cat ORDER BY id")
    print("\n=== Product categories ===")
    for r in cur.fetchall():
        print("  id={} {}".format(r["id"], r))

conn.close()
