#!/usr/bin/env python3
"""Configure + test RANFORT (8837) AI disposition webhook via API Push."""

from __future__ import annotations

import json
import os
import sys

from dotenv import load_dotenv

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
load_dotenv(os.path.join(BASE_DIR, ".env"))

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

BID = "8837"
WEBHOOK_URL = "https://crm.ranfortwellness.com/mcube/ai-disposition-webhook"

SELECTED_FIELDS = [
    "call_id",
    "agent_number",
    "quality",
    "summary",
    "insight",
    "phone_number",
    "recording",
    "total_conversation_time",
    "call_date",
    "location",
    "disposition_status",
]

FIELD_MAPPINGS = {
    "call_id": "call_id",
    "agent_number": "agent_number",
    "quality": "quality",
    "summary": "summary",
    "insight": "insight",
    "phone_number": "customer_number",
    "recording": "recording",
    "total_conversation_time": "total_conversation_time",
    "call_date": "date",
    "location": "location",
    "disposition_status": "status",
}


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() -> int:
    db = DatabaseHandler(ConfigWrapper(Config()))
    svc = ApiPushService(db)

    saved = db.save_api_push_config(BID, {
        "is_enabled": False,
        "endpoint_url": WEBHOOK_URL,
        "http_method": "POST",
        "timeout_seconds": 15,
        "auth_type": "none",
        "mapping_key": "none",
        "mapping_location": "body",
        "mapping_name": "",
        "payload_format": "flat_json",
        "payload_template": "",
        "content_type": "application/json",
        "custom_headers": {},
        "selected_fields": SELECTED_FIELDS,
        "field_mappings": FIELD_MAPPINGS,
        "include_empty_fields": 1,
    })
    print("saved_config", saved.get("endpoint_url"), "enabled=", saved.get("is_enabled"))

    with db.get_connection() as conn:
        cur = conn.cursor()
        cur.execute(
            f"SELECT callid FROM `{BID}_raw_calls` WHERE status = 3 ORDER BY call_starttime DESC LIMIT 1"
        )
        row = cur.fetchone()
    if not row:
        print("NO_ANALYZED_CALL — config saved disabled; enable after first test")
        return 0

    callid = row["callid"]
    preview = svc.preview_call_update(BID, callid)
    print("preview_success", preview.get("success"))
    print("preview_payload", json.dumps(preview.get("payload") or {}, indent=2, ensure_ascii=False)[:2000])

    result = svc.push_call_update(BID, callid, trigger_event="manual_test", force=True)
    print(
        "test_push",
        "success=", result.get("success"),
        "status=", result.get("status_code"),
        "error=", result.get("error"),
        "response=", (result.get("response_body") or "")[:300],
    )

    if result.get("success"):
        enabled = db.save_api_push_config(BID, {
            "is_enabled": True,
            "endpoint_url": WEBHOOK_URL,
            "http_method": "POST",
            "timeout_seconds": 15,
            "auth_type": "none",
            "mapping_key": "none",
            "payload_format": "flat_json",
            "payload_template": "",
            "content_type": "application/json",
            "custom_headers": {},
            "selected_fields": SELECTED_FIELDS,
            "field_mappings": FIELD_MAPPINGS,
            "include_empty_fields": 1,
        })
        print("enabled", enabled.get("is_enabled"), "effective_at", enabled.get("api_push_effective_at"))
    else:
        print("LEFT_DISABLED — fix webhook/auth and re-run test")
        return 1

    return 0


if __name__ == "__main__":
    raise SystemExit(main())
