#!/usr/bin/env python3
"""Backfill customer_callinfo when Mcube stored a short DID/trunk code instead of the real number."""

from __future__ import annotations

import argparse
import logging

import pymysql
from pymysql.cursors import DictCursor

from config import Config
from mcube_phone_util import is_plausible_phone, phone_from_callid, resolve_customer_phone

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger("backfill_short_customer_phones")


def list_target_bids(cursor, bid: str | None) -> list[str]:
    if bid:
        return [str(bid).strip()]
    cursor.execute(
        """
        SELECT DISTINCT bid
        FROM business_telephony_integrations
        WHERE is_active = 1
          AND LOWER(provider) IN ('mcube2', 'mcube_2', 'mcube_2_0', 'mcube2_0')
        ORDER BY bid
        """
    )
    return [str(row["bid"]) for row in cursor.fetchall() or []]


def backfill_bid(cursor, bid: str, *, dry_run: bool) -> int:
    table = f"`{bid}_raw_calls`"
    cursor.execute(f"SHOW TABLES LIKE %s", (f"{bid}_raw_calls",))
    if not cursor.fetchone():
        logger.warning("BID %s: table %s_raw_calls not found — skip", bid, bid)
        return 0

    cursor.execute(
        f"""
        SELECT callid, customer_callinfo, agent_callinfo, direction
        FROM {table}
        WHERE LENGTH(TRIM(COALESCE(customer_callinfo, ''))) < 6
          AND LOWER(COALESCE(direction, 'inbound')) = 'inbound'
        """
    )
    rows = cursor.fetchall() or []
    if not rows:
        logger.info("BID %s: no short customer_callinfo rows", bid)
        return 0

    updated = 0
    for row in rows:
        resolved = resolve_customer_phone(row)
        current = str(row.get("customer_callinfo") or "").strip()
        if not resolved or resolved == current or not is_plausible_phone(resolved):
            continue
        if dry_run:
            logger.info(
                "BID %s would update %s: %r -> %s",
                bid,
                row.get("callid"),
                current,
                resolved,
            )
        else:
            cursor.execute(
                f"UPDATE {table} SET customer_callinfo = %s WHERE callid = %s",
                (resolved, row["callid"]),
            )
        updated += 1
    return updated


def main() -> None:
    parser = argparse.ArgumentParser(description="Backfill short Mcube customer_callinfo values")
    parser.add_argument("--bid", help="Single BID (default: all active mcube2 BIDs)")
    parser.add_argument("--dry-run", action="store_true", help="Log changes without writing")
    args = parser.parse_args()

    cfg = Config()
    conn = pymysql.connect(
        host=cfg.DB_HOST,
        port=cfg.DB_PORT,
        user=cfg.DB_USER,
        password=cfg.DB_PASSWORD,
        database=cfg.DB_NAME,
        cursorclass=DictCursor,
    )
    try:
        cursor = conn.cursor()
        bids = list_target_bids(cursor, args.bid)
        if not bids:
            logger.warning("No target BIDs found")
            return

        total = 0
        for bid in bids:
            count = backfill_bid(cursor, bid, dry_run=args.dry_run)
            total += count
            logger.info("BID %s: %s %s row(s)", bid, "would update" if args.dry_run else "updated", count)

        if not args.dry_run:
            conn.commit()
        logger.info("Done — %s row(s) %s", total, "previewed" if args.dry_run else "updated")
    finally:
        conn.close()


if __name__ == "__main__":
    main()
