"""Classifier Agent — adds metadata tags to extracted signals."""
import logging
from backend.providers import call_llm
from backend.db.models import Signal
from backend.agents.json_utils import extract_json_object

logger = logging.getLogger("thirdeye.agents.classifier")

SYSTEM_PROMPT = """You are a fast metadata classifier. Given an extracted signal, add classification tags.

Respond ONLY with valid JSON (no markdown, no backticks):
{"sentiment": "positive|neutral|negative|urgent", "urgency": "none|low|medium|high|critical", "keywords": ["3-5 searchable keywords"]}
"""


async def classify_signal(signal: Signal) -> Signal:
    """Add classification metadata to a signal."""
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": f"Classify this signal:\nType: {signal.type}\nSummary: {signal.summary}\nQuote: {signal.raw_quote}"},
    ]

    try:
        result = await call_llm("fast_small", messages, temperature=0.1, max_tokens=200)
        parsed = extract_json_object(result.get("content", ""))
        signal.sentiment = parsed.get("sentiment", signal.sentiment)
        signal.urgency = parsed.get("urgency", signal.urgency)
        signal.keywords = parsed.get("keywords", signal.keywords)

    except Exception as e:
        logger.warning(f"Classification failed, using defaults: {e}")
        # Keep defaults — classification failure is non-fatal

    return signal
