"""Reflection — pre-plan clarification check. Max 2 questions."""

import json
import re

import structlog

from fliiq.runtime.llm.providers import BaseLLM

log = structlog.get_logger()

_REFLECTION_PROMPT = """Analyze the user's request. Determine if you have enough information to create a good plan.

Respond with ONLY valid JSON:
{
  "ready": true/false,
  "questions": ["question1", "question2"]
}

Rules:
- If the task is clear enough to plan, set ready=true and questions=[]
- If critical information is missing, set ready=false and list 1-2 specific questions
- Never ask more than 2 questions
- Only ask about things that would fundamentally change the plan
- Don't ask about implementation details — those belong in the plan itself"""


def _extract_json(text: str) -> dict:
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass
    match = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)
    if match:
        try:
            return json.loads(match.group(1))
        except json.JSONDecodeError:
            pass
    # Default: assume ready if we can't parse
    log.warning("reflection_parse_failed", response=text[:200])
    return {"ready": True, "questions": []}


async def reflect(llm: BaseLLM, prompt: str, system: str) -> tuple[bool, list[str]]:
    """Check if prompt needs clarification before planning.

    Returns (ready, questions). Max 2 questions.
    """
    combined_system = f"{system}\n\n{_REFLECTION_PROMPT}"
    messages = [{"role": "user", "content": prompt}]

    response = await llm.generate(messages, system=combined_system)
    result = _extract_json(response.content)

    ready = result.get("ready", True)
    questions = result.get("questions", [])[:2]

    log.debug("reflection_result", ready=ready, question_count=len(questions))
    return ready, questions
