import json
import os
import sys
from pathlib import Path

import requests


BASE_URL = os.getenv("CLIENTFLOW_BASE_URL", "http://127.0.0.1:8000")


CASES = [
    {
        "conversation_id": "case-send-invoice",
        "message": "Recebemos o equipamento. Agradecemos o envio da factura.",
    },
    {
        "conversation_id": "case-payment",
        "message": "Segue comprovativo de pagamento em anexo.",
    },
    {
        "conversation_id": "case-info",
        "message": "Bom dia, podem enviar mais informações sobre carregadores monofásicos?",
    },
    {
        "conversation_id": "case-shipment",
        "message": "Boa tarde, gostava de saber se já enviaram o carregador.",
    },
]


def main() -> int:
    out_dir = Path("resultados-action-core")
    out_dir.mkdir(exist_ok=True)

    rows = []

    for case in CASES:
        payload = {
            "last_customer_message": case["message"],
            "previous_context": "Teste Action Core.",
            "source": "manual_test",
            "conversation_id": case["conversation_id"],
            "contact_id": "test-contact",
        }

        response = requests.post(
            f"{BASE_URL}/analyze",
            headers={"Content-Type": "application/json"},
            json=payload,
            timeout=90,
        )

        response.raise_for_status()
        data = response.json()

        action_decision = data.get("action_decision") or {}
        action_result = data.get("action_result") or {}

        row = {
            "conversation_id": case["conversation_id"],
            "action_code": action_decision.get("action_code"),
            "route": action_result.get("route"),
            "action": action_result.get("action"),
            "safe_to_post": action_result.get("safe_to_post"),
            "task_id": data.get("task_id"),
            "needs_review": data.get("needs_review"),
        }

        rows.append(row)

        print("=" * 80)
        print(case["conversation_id"])
        print("action_code:", row["action_code"])
        print("route:", row["route"])
        print("action:", row["action"])
        print("safe_to_post:", row["safe_to_post"])
        print("task_id:", row["task_id"])

        (out_dir / f"{case['conversation_id']}.json").write_text(
            json.dumps(data, ensure_ascii=False, indent=2),
            encoding="utf-8",
        )

    (out_dir / "summary.json").write_text(
        json.dumps(rows, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )

    print("\nResumo:", out_dir / "summary.json")
    return 0


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