"""Integration test for shipping-policy routing in agent chat.

Goal:
- Ask: "ship ve Hai Phong bao lau"
- Verify agent response includes shipping-policy facts
- Fail when response is hotline-only redirect
- Always print raw JSON for debugging
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import time
import unicodedata
from typing import Any

import requests

DEFAULT_API_URL = "http://localhost:5000"
CHAT_ENDPOINT = "/api/agent/chat-dev"
DEFAULT_QUERY = "ship ve Hai Phong bao lau"
DEFAULT_TOKEN = "071w198x23ict4hs1i6bl889fit5p3f7"
DEFAULT_TIMEOUT = 90

# If answer only contains hotline escalation and no shipping-policy facts -> FAIL.
HOTLINE_PATTERNS = [
    r"1800\s*6061",
    r"hotline",
    r"saleonline@canifa\.com",
    r"lien he",
]

# Signals that answer used policy data instead of only escalation.
SHIPPING_FACT_PATTERNS = [
    r"hai\s*phong",
    r"phi\s*van\s*chuyen",
    r"thoi\s*gian\s*giao\s*hang",
    r"3\s*(den|-|to)\s*7\s*ngay",
    r"30\.?000",
    r"599\.?000",
    r"freeship",
]


def _normalize(text: str) -> str:
    raw = (text or "").strip().lower()
    no_accents = "".join(ch for ch in unicodedata.normalize("NFD", raw) if unicodedata.category(ch) != "Mn")
    return re.sub(r"\s+", " ", no_accents)


def _has_any(patterns: list[str], text: str) -> bool:
    return any(re.search(pattern, text, flags=re.IGNORECASE) for pattern in patterns)


def _is_hotline_only_redirect(ai_response: str) -> bool:
    text = _normalize(ai_response)
    has_hotline = _has_any(HOTLINE_PATTERNS, text)
    has_shipping_fact = _has_any(SHIPPING_FACT_PATTERNS, text)
    return has_hotline and not has_shipping_fact


def run_shipping_policy_test(api_url: str, token: str, query: str, timeout: int) -> int:
    url = f"{api_url}{CHAT_ENDPOINT}"
    payload: dict[str, Any] = {"user_query": query, "images": []}
    headers = {"Content-Type": "application/json"}
    if token:
        headers["Authorization"] = f"Bearer {token}"

    print("=" * 72)
    print("TEST: Agent shipping-policy routing")
    print(f"URL   : {url}")
    print(f"QUERY : {query}")
    print("=" * 72)

    start = time.time()
    try:
        response = requests.post(url, json=payload, headers=headers, timeout=timeout)
    except Exception as exc:
        print(f"FAIL: request error: {exc}")
        return 2

    elapsed_ms = int((time.time() - start) * 1000)
    print(f"HTTP  : {response.status_code} ({elapsed_ms} ms)")

    try:
        data = response.json()
    except Exception:
        print("FAIL: response is not valid JSON")
        print(response.text[:1000])
        return 2

    print("\nRAW JSON:")
    print(json.dumps(data, ensure_ascii=False, indent=2))

    if response.status_code != 200:
        print("\nFAIL: non-200 response")
        return 1

    ai_response = str(data.get("ai_response", ""))
    ai_norm = _normalize(ai_response)

    hotline_only = _is_hotline_only_redirect(ai_response)
    has_shipping_fact = _has_any(SHIPPING_FACT_PATTERNS, ai_norm)

    print("\nCHECKS:")
    print(f"- has shipping fact    : {has_shipping_fact}")
    print(f"- hotline-only redirect: {hotline_only}")

    if hotline_only:
        print("\nFAIL: agent returned hotline-only redirect for shipping-policy question")
        return 1

    if not has_shipping_fact:
        print("\nFAIL: answer does not show shipping-policy facts")
        return 1

    print("\nPASS: agent returned shipping-policy information (not hotline-only)")
    return 0


def main() -> None:
    parser = argparse.ArgumentParser(description="Test shipping-policy question routing in agent")
    parser.add_argument("--api-url", default=DEFAULT_API_URL, help=f"API base URL (default: {DEFAULT_API_URL})")
    parser.add_argument("--token", default=DEFAULT_TOKEN, help="Bearer token for API (optional)")
    parser.add_argument("--query", default=DEFAULT_QUERY, help=f"Question to test (default: {DEFAULT_QUERY})")
    parser.add_argument(
        "--timeout", type=int, default=DEFAULT_TIMEOUT, help=f"Request timeout seconds (default: {DEFAULT_TIMEOUT})"
    )

    args = parser.parse_args()
    code = run_shipping_policy_test(
        api_url=args.api_url,
        token=args.token,
        query=args.query,
        timeout=args.timeout,
    )
    sys.exit(code)


if __name__ == "__main__":
    main()
