"""Grounded market-context summariser.

Extracts only claims that are verbatim-supported by the raw search results.
Each claim carries the source URL and a verbatim quote — no quote, no claim.
"""

import os
from pathlib import Path  # noqa: F401 — used by load_dotenv path resolution
from typing import Literal

from dotenv import load_dotenv
from pydantic import BaseModel
from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.litellm import LiteLLMProvider

from backend.chanakya.rt_agent.log_utils import write_log

load_dotenv(Path(__file__).resolve().parents[3] / ".env", override=False)

_SYSTEM = """\
You are a strict evidence extractor. You receive web search results and a question.

Rules:
- Each claim MUST include a verbatim_quote copied exactly from the source text.
- Each claim MUST include the source_url of the result it came from.
- If you cannot find a verbatim quote to support a claim, DO NOT include it.
- DO NOT use your training data, general knowledge, or inference.
- DO NOT paraphrase and call it a quote — it must be exact text from the source.
- If the search results contain no relevant benchmarks or figures, return an empty list.

Relevance scoring — rate each claim against the user's question:
- high:   claim directly answers or benchmarks the metric asked (e.g. a specific % or rate for that topic)
- medium: claim is related context but not the exact metric (e.g. describes the process, mentions the topic without figures)
- low:    claim is tangentially related — same domain but different metric or time period
"""


class GroundedClaim(BaseModel):
    claim: str
    verbatim_quote: str
    source_url: str
    relevance: Literal["high", "medium", "low"]


class GroundedSummary(BaseModel):
    claims: list[GroundedClaim]


def _make_agent() -> Agent[None, GroundedSummary]:
    model = OpenAIChatModel(
        os.environ.get("LITELLM_PROVIDER_MODEL_NAME", ""),
        provider=LiteLLMProvider(
            api_base=os.environ.get("LITELLM_PROVIDER_BASE_URL", ""),
            api_key=os.environ.get("LITELLM_API_KEY", ""),
        ),
    )
    return Agent(model, output_type=GroundedSummary, system_prompt=_SYSTEM, retries=0)


_agent = _make_agent()


def summarise(query: str, search_results: str) -> tuple[str, list[dict[str, str]]]:
    """Extract grounded claims from search results.

    Returns:
        (text_for_llm, structured_claims) where text_for_llm is a bullet-point
        string for the LLM's context and structured_claims is a list of dicts
        with keys: relevance, claim, source_url.
    """
    user_msg = f"Question: {query}\n\nSearch results:\n{search_results}"
    result = _agent.run_sync(user_msg, model_settings={"temperature": 0})
    summary = result.output

    if not summary.claims:
        write_log("web-summariser", {"query": query, "claims": [], "market_context": ""})
        return "", []

    structured = [
        {"relevance": c.relevance.upper(), "claim": c.claim, "source_url": c.source_url}
        for c in summary.claims
    ]
    bullets = "\n".join(
        f"- [{c['relevance']}] {c['claim']} (source: {c['source_url']})"
        for c in structured
    )
    write_log("web-summariser", {"query": query, "claims": [c.model_dump() for c in summary.claims], "market_context": bullets})
    return bullets, structured
