#!/usr/bin/env python3
"""Ensure summary config DB columns exist and test save for a BID."""

import argparse
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))

from config import Config  # noqa: E402
from db_handler import DatabaseHandler  # noqa: E402


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()
    parser.add_argument("--bid", default="6004")
    parser.add_argument("--mode", default="discovery_recap", choices=["default", "discovery_recap", "custom"])
    parser.add_argument("--instructions", default="")
    args = parser.parse_args()

    db = DatabaseHandler(ConfigWrapper(Config()))
    print("Ensuring business_pipeline_config table and columns...")
    db.ensure_business_pipeline_config_table()

    with db.get_connection() as conn:
        cursor = conn.cursor()
        cursor.execute(
            """
            SELECT column_name FROM information_schema.columns
            WHERE table_schema = DATABASE()
              AND table_name = 'business_pipeline_config'
              AND column_name IN ('summary_mode', 'summary_instructions')
            """
        )
        cols = {row.get("column_name") or row.get("COLUMN_NAME") for row in (cursor.fetchall() or [])}
        print("Summary columns present:", sorted(cols))
        if "summary_mode" not in cols:
            print("ERROR: summary_mode column missing after ensure.")
            sys.exit(1)

    instructions = args.instructions.strip() or None
    if args.mode == "custom" and not instructions:
        print("ERROR: --instructions required for custom mode")
        sys.exit(1)

    print(f"Saving summary_mode={args.mode!r} for bid={args.bid!r}...")
    db.save_summary_config(args.bid, args.mode, instructions)

    cfg = db.get_pipeline_config(args.bid)
    print("Saved row:", {k: cfg.get(k) for k in ("bid", "summary_mode", "summary_instructions") if cfg})
    print("OK")


if __name__ == "__main__":
    main()
