"""B3: Prompt Quality Assessment using LLM (gpt-4o-mini).

Only runs for sessions with interrupts or AI clarification requests.
"""

import json
import os

from dotenv import load_dotenv

from .base import BaseAnalyzer
from .helpers import get_first_user_prompt, detect_interrupt_pattern
from .llm_cache import get_cached, set_cache

load_dotenv(os.path.join(os.path.dirname(__file__), "..", "..", ".prod.env"), override=True)

VALID_QUALITIES = {"clear", "vague", "missing_context"}

SYSTEM_PROMPT = """You assess the quality of prompts given to AI coding assistants.
Given the first user prompt from a coding session that had issues (interruptions or AI confusion), assess:

1. prompt_quality: one of "clear", "vague", "missing_context"
2. prompt_improvement_suggestion: one-line suggestion for how the prompt could have been better

Respond with ONLY valid JSON, no markdown:
{"prompt_quality": "...", "prompt_improvement_suggestion": "..."}"""

CLARIFICATION_PATS = [
    "would you like me to", "do you want me to", "should i ",
    "could you clarify", "which one", "before i proceed", "would you prefer",
]


class PromptQualityAnalyzer(BaseAnalyzer):
    name = "b03_prompt_quality"

    def analyze(self, sessions_df, messages_df, tool_calls_df, tool_results_df, token_usage_df) -> dict:
        try:
            from openai import OpenAI
            api_key = os.environ.get("OPENAI_API_KEY")
            if not api_key:
                return {"error": "OPENAI_API_KEY not set", "per_session": []}
            client = OpenAI()
        except ImportError:
            return {"error": "openai package not installed", "per_session": []}

        per_session = []
        stats = {"total": 0, "skipped": 0, "cached": 0, "llm_called": 0, "errors": 0}

        for session in self.iter_sessions(sessions_df):
            sid = session["id"]
            source = session.get("source") or ""
            stats["total"] += 1

            stream = self.build_message_stream(messages_df, tool_calls_df, tool_results_df, sid)
            if not stream:
                stats["skipped"] += 1
                continue

            # Check if session qualifies (has interrupts or AI clarification)
            has_interrupt = any(
                detect_interrupt_pattern(m.get("result_output") or "") is not None
                for m in stream if m["msg_type"] == "tool_result"
            )
            has_clarification = any(
                any(pat in (m.get("content") or "").lower() for pat in CLARIFICATION_PATS)
                for m in stream if m["msg_type"] == "assistant"
            )

            if not has_interrupt and not has_clarification:
                stats["skipped"] += 1
                continue

            msg_list = [{**m, "msg_type": m["msg_type"]} for m in stream]
            first_prompt = get_first_user_prompt(msg_list, source)
            if not first_prompt:
                stats["skipped"] += 1
                continue

            cache_key = f"prompt_quality:{first_prompt}"
            cached = get_cached(cache_key)
            if cached:
                stats["cached"] += 1
                per_session.append({"session_id": sid, **cached})
                continue

            try:
                resp = client.chat.completions.create(
                    model="gpt-4o-mini", temperature=0,
                    messages=[
                        {"role": "system", "content": SYSTEM_PROMPT},
                        {"role": "user", "content": first_prompt[:4000]},
                    ],
                )
                result = json.loads(resp.choices[0].message.content.strip())
                if result.get("prompt_quality") not in VALID_QUALITIES:
                    result["prompt_quality"] = "vague"
                set_cache(cache_key, result)
                stats["llm_called"] += 1
                per_session.append({"session_id": sid, **result})
            except Exception as e:
                stats["errors"] += 1
                print(f"  [b03] LLM error for {sid[:8]}: {e}")

        print(f"  [b03] Stats: {stats}")
        return {"stats": stats, "total_sessions": len(per_session), "per_session": per_session}
