#!/usr/bin/env python3
import json
import os
from datetime import datetime, timezone
from pathlib import Path

import requests

API_URL = os.getenv("BIBLE_CHAT_URL", "https://apis.pikzulstudios.com/api/chat")
API_KEY = os.getenv("BIBLE_API_SECRET", "")
TIMEOUT_SECONDS = int(os.getenv("BIBLE_CHAT_MONITOR_TIMEOUT", "45"))
LOG_PATH = Path(os.getenv("BIBLE_CHAT_MONITOR_LOG", "data/chat_health_monitor.jsonl"))

FALLBACK_MARKERS = (
    "temporary connection issue",
    "try again in a few seconds",
    "bible-companion (fallback)",
)


def utc_now() -> str:
    return datetime.now(timezone.utc).isoformat()


def classify(status_code: int, response_text: str) -> str:
    body = (response_text or "").lower()
    if status_code != 200:
        return "error"
    if any(marker in body for marker in FALLBACK_MARKERS):
        return "degraded"
    return "ok"


def append_log(entry: dict) -> None:
    LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
    with LOG_PATH.open("a", encoding="utf-8") as output:
        output.write(json.dumps(entry, ensure_ascii=False) + "\n")


def main() -> int:
    if not API_KEY:
        print("BIBLE_API_SECRET is missing")
        return 2

    payload = {
        "message": "Health probe: respond with one short verse.",
        "conversation_id": "health-monitor",
        "include_doctrinal_context": True,
    }
    headers = {
        "x-api-key": API_KEY,
        "Accept": "application/json",
        "Content-Type": "application/json",
        "User-Agent": "BibleHealthMonitor/1.0",
    }

    started = datetime.now(timezone.utc)
    entry = {
        "timestamp": utc_now(),
        "url": API_URL,
        "status": "error",
        "http_status": None,
        "latency_ms": None,
        "response_preview": None,
        "error": None,
    }

    try:
        response = requests.post(API_URL, json=payload, headers=headers, timeout=TIMEOUT_SECONDS)
        elapsed_ms = int((datetime.now(timezone.utc) - started).total_seconds() * 1000)
        text = response.text or ""

        entry.update(
            {
                "http_status": response.status_code,
                "latency_ms": elapsed_ms,
                "response_preview": text[:300],
                "status": classify(response.status_code, text),
            }
        )
    except Exception as exc:
        elapsed_ms = int((datetime.now(timezone.utc) - started).total_seconds() * 1000)
        entry.update({"latency_ms": elapsed_ms, "error": repr(exc)})

    append_log(entry)

    status = entry["status"]
    code = entry["http_status"]
    print(f"[{entry['timestamp']}] status={status} http={code} latency_ms={entry['latency_ms']}")
    if entry["error"]:
        print(f"error={entry['error']}")

    return 0 if status == "ok" else 1


if __name__ == "__main__":
    raise SystemExit(main())
