"""
Backfill agent_callinfo/customer_callinfo from callto/callfrom columns in raw_calls.

This script checks for available source columns (callto/callfrom or call_to/call_from)
and only updates rows where the target fields are empty.
"""
import argparse

from config import Config
from db_handler import DatabaseHandler


def pick_column(columns, candidates):
    lower_map = {col.lower(): col for col in columns}
    for candidate in candidates:
        if candidate.lower() in lower_map:
            return lower_map[candidate.lower()]
    return None


def main():
    parser = argparse.ArgumentParser(description="Backfill call info from callto/callfrom.")
    parser.add_argument("--bid", default="1713", help="Business ID (default: 1713)")
    args = parser.parse_args()

    config = Config()
    db_handler = DatabaseHandler(config)

    with db_handler.get_connection() as conn:
        cursor = conn.cursor()

        cursor.execute(f"SHOW COLUMNS FROM `{args.bid}_raw_calls`")
        columns = [row["Field"] for row in cursor.fetchall()]

        callto_col = pick_column(columns, ["callto", "call_to"])
        callfrom_col = pick_column(columns, ["callfrom", "call_from"])

        if not callto_col or not callfrom_col:
            missing = []
            if not callto_col:
                missing.append("callto/call_to")
            if not callfrom_col:
                missing.append("callfrom/call_from")
            print(f"Missing source columns in `{args.bid}_raw_calls`: {', '.join(missing)}")
            return

        update_query = f"""
            UPDATE `{args.bid}_raw_calls`
            SET
                customer_callinfo = CASE
                    WHEN customer_callinfo IS NULL OR customer_callinfo = ''
                    THEN `{callto_col}`
                    ELSE customer_callinfo
                END,
                agent_callinfo = CASE
                    WHEN agent_callinfo IS NULL OR agent_callinfo = ''
                    THEN `{callfrom_col}`
                    ELSE agent_callinfo
                END
            WHERE
                (`{callto_col}` IS NOT NULL AND `{callto_col}` != '')
                OR (`{callfrom_col}` IS NOT NULL AND `{callfrom_col}` != '')
        """

        cursor.execute(update_query)
        conn.commit()
        print(f"Updated {cursor.rowcount} rows in `{args.bid}_raw_calls`.")


if __name__ == "__main__":
    main()
