"""
Backfill BANT profiles from {bid}_callanalytics.raw_response into {bid}_bant.
"""
import argparse
import json

from config import Config
from db_handler import DatabaseHandler


class ConfigWrapper:
    def __init__(self, config):
        self._config = config

    def get(self, key, default=None):
        return getattr(self._config, key, default)

    def __getattr__(self, key):
        return getattr(self._config, key)


def main():
    parser = argparse.ArgumentParser(description="Backfill BANT from callanalytics.")
    parser.add_argument("--bid", default="1713", help="Business ID (default: 1713)")
    args = parser.parse_args()

    config = Config()
    db_handler = DatabaseHandler(ConfigWrapper(config))

    with db_handler.get_connection() as conn:
        cursor = conn.cursor()
        query = f"""
            SELECT callid, raw_response
            FROM `{args.bid}_callanalytics`
            WHERE raw_response IS NOT NULL
        """
        cursor.execute(query)
        rows = cursor.fetchall()

    updated = 0
    skipped = 0

    for row in rows:
        raw_response = row.get('raw_response')
        if not raw_response:
            skipped += 1
            continue

        try:
            payload = json.loads(raw_response) if isinstance(raw_response, str) else raw_response
        except Exception:
            skipped += 1
            continue

        profile = payload.get('customer_profile')
        summary = payload.get('customer_profile_summary', '')
        if not profile and not summary:
            skipped += 1
            continue

        db_handler.save_bant_analysis(args.bid, row['callid'], profile, summary)
        updated += 1

    print(f"Backfill complete. Updated: {updated}, Skipped: {skipped}")


if __name__ == "__main__":
    main()
