"""
test_summarizer.py

Manual end-to-end test for the conversation summarizer.
Reads a conversation from a .txt file, calls your Azure LLM,
and prints the plain-text summary output.

Usage:
    python test_summarizer.py

Required environment variables:
    AZURE_OPENAI_ENDPOINT    e.g. https://my-resource.openai.azure.com/
    AZURE_OPENAI_API_KEY     your Azure API key
    AZURE_OPENAI_DEPLOYMENT  your deployment / model name
    AZURE_OPENAI_API_VERSION (optional, defaults to 2024-02-01)
"""

import os
import sys

# ── 1. Check env vars before importing anything ──────────────────────────────
REQUIRED = ["AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_API_KEY", "AZURE_OPENAI_DEPLOYMENT"]
missing = [v for v in REQUIRED if not os.environ.get(v)]
if missing:
    print("ERROR: Missing required environment variables:")
    for v in missing:
        print(f"  export {v}=<your value>")
    sys.exit(1)

# ── 2. Imports ────────────────────────────────────────────────────────────────
from openai import AzureOpenAI
from .conversation_summarizer import ConversationSummarizer, LLMClient

# ── 3. Wire up the client ─────────────────────────────────────────────────────
azure_raw = AzureOpenAI(
    azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
    api_key=os.environ["AZURE_OPENAI_API_KEY"],
    api_version=os.environ.get("AZURE_OPENAI_API_VERSION", "2024-02-01"),
)
llm_client = LLMClient(client=azure_raw, model=os.environ["AZURE_OPENAI_DEPLOYMENT"])
summarizer = ConversationSummarizer(llm_client)

# ── 4. Read the conversation file ─────────────────────────────────────────────
# default to sample_conversation.txt located next to this script; makes the
# module behave the same regardless of the current working directory.
CONVERSATION_FILE = os.path.join(os.path.dirname(__file__), "sample_conversation.txt")

if not os.path.exists(CONVERSATION_FILE):
    print(f"ERROR: Conversation file not found: {CONVERSATION_FILE}")
    sys.exit(1)

with open(CONVERSATION_FILE, "r", encoding="utf-8") as f:
    conversation_text = f.read()

print(f"Loaded conversation from: {CONVERSATION_FILE}")
print(f"Length: {len(conversation_text)} characters, {len(conversation_text.splitlines())} lines")
print("─" * 50)
print("Calling Azure LLM to summarize...")
print("─" * 50)

# ── 5. Summarize ──────────────────────────────────────────────────────────────
try:
    summary_text = summarizer.summarize_to_text(conversation_text)
except ValueError as e:
    print(f"ERROR: {e}")
    sys.exit(1)

# ── 6. Print output ───────────────────────────────────────────────────────────
print("\nOUTPUT\n")
print(summary_text)
print("\n" + "─" * 50)

# ── 7. Basic output checks ────────────────────────────────────────────────────
print("\nSanity checks:")

checks = [
    ("Output is non-empty",            bool(summary_text.strip())),
    ("Contains 'Summary' header",       "Summary" in summary_text),
    ("Contains user intent",            "User intent:" in summary_text),
    ("At least one key decision found", "Key decisions:" in summary_text),
    ("At least one action item found",  "Action items:" in summary_text),
    ("Mentions leave management topic", any(
        kw in summary_text.lower()
        for kw in ["leave", "django", "employee", "approval", "csv", "postgresql"]
    )),
]

all_passed = True
for label, result in checks:
    status = "PASS" if result else "FAIL"
    if not result:
        all_passed = False
    print(f"  [{status}]  {label}")

print()
if all_passed:
    print("All checks passed. Summary looks good!")
else:
    print("Some checks failed. Review the output above.")
