"""AI News Intelligence Agent (Platform Expansion v2, Module 1).

Evaluates recent headlines for the symbol and produces a 0-100 news score
plus explicit positive/negative catalysts. Feeds the ensemble decision
layer as one weighted input — per the spec, news adjusts confidence but
never unilaterally overrides a technical setup.
"""
import os

from .base import Agent, AgentResult
from ..services.llm import llm_available, score_sentiment
from ..services.news import get_news_provider, heuristic_news_score


def news_enabled() -> bool:
    return os.getenv("NEWS_ENABLED", "true").lower() == "true"


class NewsAgent(Agent):
    name = "news"

    def run(self, context: dict) -> AgentResult:
        symbol = context["symbol"]
        if not news_enabled():
            return AgentResult(agent=self.name, score=50.0,
                               data={"method": "disabled"},
                               notes=["News analysis disabled (NEWS_ENABLED=false) — neutral"])

        headlines = get_news_provider().get_news(symbol)
        if not headlines:
            return AgentResult(agent=self.name, score=50.0, data={"method": "no-news"},
                               notes=["No recent headlines — news-neutral"])

        result = None
        if llm_available():
            digest = "; ".join(h["headline"] for h in headlines[:6])[:900]
            llm = score_sentiment(symbol, f"Recent headlines: {digest}")
            if llm:
                result = {
                    "score": round((llm["sentiment"] + 1) / 2 * 100, 1),
                    "positive_catalysts": [], "negative_catalysts": [],
                    "method": "llm",
                    "reason": llm["reason"],
                }
        if result is None:
            result = heuristic_news_score(headlines)

        score = result["score"]
        direction = "CALL" if score >= 65 else "PUT" if score <= 35 else None
        notes = [f"News score {score} ({result['method']}, {len(headlines)} headlines)"]
        for h in result.get("positive_catalysts", []):
            notes.append(f"＋ {h}")
        for h in result.get("negative_catalysts", []):
            notes.append(f"－ {h}")
        if result.get("reason"):
            notes.append(f"LLM: {result['reason']}")

        return AgentResult(
            agent=self.name, score=score, direction=direction,
            data={"method": result["method"],
                  "headlines": [h["headline"] for h in headlines[:5]],
                  "positive_catalysts": result.get("positive_catalysts", []),
                  "negative_catalysts": result.get("negative_catalysts", [])},
            notes=notes,
        )
