"""
FinClaw — LLM-Enhanced Stock Analysis
==========================================
Uses AI (Claude/GPT) to analyze:
1. Industry disruption risk (AI replacing their business?)
2. AI beneficiary score (Does AI make them MORE valuable?)
3. Competitive moat in AI era
4. Narrative strength (self-reinforcing loop?)

This creates a "disruption factor" that traditional quant can't capture.

Example insights LLM can provide:
- "Salesforce faces AI agent disruption → AVOID"
- "NVIDIA is the picks-and-shovels play for AI → STRONG BUY"
- "Cambricon is China's NVIDIA bet, geopolitical premium → BUY with risk"
- "Moutai has zero AI relevance, but consumption moat → HOLD"
"""
import json, sys, os
from dataclasses import dataclass
from typing import Optional


@dataclass
class DisruptionAnalysis:
    ticker: str
    name: str
    ai_beneficiary_score: float  # -1 (disrupted) to +1 (AI winner)
    moat_score: float  # 0 to 1
    narrative_score: float  # -1 to 1
    disruption_risk: float  # 0 to 1 (high = being disrupted)
    reasoning: str
    sector_theme: str


# Pre-computed disruption analysis for major stocks
# In production, this would be generated by LLM API calls
# For now, we use expert-curated assessments
DISRUPTION_DB = {
    # ═══ AI WINNERS (beneficiary_score > 0.7) ═══
    "NVDA": DisruptionAnalysis("NVDA", "NVIDIA", 0.95, 0.90, 0.95, 0.05,
        "Monopoly on AI training hardware. Every AI company needs NVIDIA GPUs. "
        "CUDA moat is 15+ years deep. Risk: custom ASICs from Google/Amazon.",
        "AI Infrastructure"),
    "AVGO": DisruptionAnalysis("AVGO", "Broadcom", 0.85, 0.80, 0.80, 0.10,
        "Custom AI chips (Google TPU, Meta MTIA). Networking for AI datacenters. "
        "VMware acquisition adds enterprise software moat.",
        "AI Infrastructure"),
    "ANET": DisruptionAnalysis("ANET", "Arista Networks", 0.80, 0.75, 0.70, 0.10,
        "AI datacenter networking backbone. Every GPU cluster needs Arista switches. "
        "400G/800G ethernet for AI training clusters.",
        "AI Infrastructure"),
    "AMD": DisruptionAnalysis("AMD", "AMD", 0.75, 0.65, 0.70, 0.15,
        "MI300X competing with NVIDIA in AI inference. Strong CPU position. "
        "Risk: always #2 to NVIDIA in AI training.",
        "AI Infrastructure"),
    "PLTR": DisruptionAnalysis("PLTR", "Palantir", 0.80, 0.70, 0.85, 0.10,
        "AI platform for government and enterprise. AIP (AI Platform) is killer product. "
        "Unique position: only company with both gov clearance + AI platform.",
        "AI Software"),
    "META": DisruptionAnalysis("META", "Meta", 0.70, 0.80, 0.60, 0.15,
        "Massive AI investment (Llama models, AI-generated content, Reels AI). "
        "3B+ users = unmatched training data. Risk: regulatory, metaverse distraction.",
        "AI Platform"),
    "GOOG": DisruptionAnalysis("GOOG", "Alphabet", 0.75, 0.85, 0.50, 0.20,
        "Gemini AI, DeepMind research. But search disruption risk from AI chatbots. "
        "Waymo is hidden AI gem. Cloud AI is strong.",
        "AI Platform"),
    "NFLX": DisruptionAnalysis("NFLX", "Netflix", 0.40, 0.70, 0.50, 0.15,
        "AI for content recommendation (huge moat). AI-generated content is future. "
        "Not directly AI infra, but AI improves their core product significantly.",
        "AI-Enhanced Consumer"),

    # ═══ AI-ENHANCED TRADITIONAL (0.3-0.7) ═══
    "COST": DisruptionAnalysis("COST", "Costco", 0.15, 0.85, 0.30, 0.05,
        "AI won't disrupt physical retail with membership moat. AI helps supply chain. "
        "Recession-resistant, inflation hedge. Not AI play but safe.",
        "Defensive Consumer"),
    "WMT": DisruptionAnalysis("WMT", "Walmart", 0.25, 0.80, 0.35, 0.10,
        "Heavy AI investment in supply chain, autonomous delivery. Scale advantage. "
        "E-commerce + physical hybrid model is defensible.",
        "AI-Enhanced Retail"),
    "LLY": DisruptionAnalysis("LLY", "Eli Lilly", 0.35, 0.85, 0.70, 0.05,
        "GLP-1 drugs (Mounjaro/Zepbound) are biggest pharma story in decades. "
        "AI helps drug discovery but Lilly's moat is clinical pipeline, not AI.",
        "Pharma Innovation"),
    "XOM": DisruptionAnalysis("XOM", "ExxonMobil", 0.05, 0.70, 0.20, 0.10,
        "Zero AI relevance. Energy demand stays regardless of AI. "
        "AI datacenters actually INCREASE energy demand. Counter-intuitive beneficiary.",
        "Energy"),
    "JPM": DisruptionAnalysis("JPM", "JPMorgan", 0.30, 0.75, 0.30, 0.20,
        "Heavy AI investment in trading, risk management. But fintech disruption risk. "
        "Too big to fail. AI makes banking more efficient.",
        "AI-Enhanced Finance"),

    # ═══ AI DISRUPTION VICTIMS (beneficiary < 0) ═══
    "CRM": DisruptionAnalysis("CRM", "Salesforce", -0.30, 0.50, -0.40, 0.60,
        "CRITICAL RISK: AI agents replacing traditional CRM seat-based model. "
        "Why pay $300/seat when AI agent does the work? Agentforce is defensive move.",
        "SaaS Disrupted"),
    "SHOP": DisruptionAnalysis("SHOP", "Shopify", -0.10, 0.55, -0.20, 0.40,
        "AI can build e-commerce sites automatically. Shopify's moat is ecosystem, "
        "not technology. AI commoditizes what Shopify sells.",
        "SaaS At Risk"),
    "INTC": DisruptionAnalysis("INTC", "Intel", -0.20, 0.30, -0.50, 0.50,
        "Lost AI GPU race to NVIDIA. Foundry strategy struggling. "
        "AI has moved to GPUs, leaving CPU-centric Intel behind.",
        "Legacy Tech"),

    # ═══ CHINA A-SHARES ═══
    "688256.SS": DisruptionAnalysis("688256.SS", "Cambricon", 0.85, 0.40, 0.90, 0.20,
        "China's #1 AI chip company. Geopolitical premium: China MUST have domestic AI chips. "
        "Government backing. Risk: still far behind NVIDIA technically. "
        "Narrative: 'China's NVIDIA' drives extreme valuation premium.",
        "China AI Infrastructure"),
    "603019.SS": DisruptionAnalysis("603019.SS", "Zhongke Shuguang", 0.75, 0.50, 0.80, 0.15,
        "China's AI server leader. Every Chinese AI lab buys Sugon servers. "
        "US sanctions actually help (domestic substitution). Government customer base.",
        "China AI Infrastructure"),
    "002371.SZ": DisruptionAnalysis("002371.SZ", "Naura Tech", 0.60, 0.60, 0.65, 0.15,
        "Semiconductor equipment maker. China's ASML ambition. "
        "AI chip demand → more fab equipment needed. Sanctions beneficiary.",
        "China Semiconductor"),
    "300750.SZ": DisruptionAnalysis("300750.SZ", "CATL", 0.30, 0.80, 0.60, 0.10,
        "World's largest battery maker. AI doesn't disrupt batteries. "
        "EV + energy storage secular trend. Strong moat via scale + tech.",
        "Clean Energy"),
    "002594.SZ": DisruptionAnalysis("002594.SZ", "BYD", 0.35, 0.75, 0.55, 0.10,
        "EV + autonomous driving (AI-enhanced). Vertical integration moat. "
        "AI helps their autonomous driving stack. Strong China + global expansion.",
        "EV / AI-Enhanced"),
    "601899.SS": DisruptionAnalysis("601899.SS", "Zijin Mining", 0.05, 0.70, 0.40, 0.05,
        "Gold/copper mining. Zero AI disruption risk. "
        "AI datacenters need copper → counter-intuitive beneficiary. Gold is hedge.",
        "Resources"),
    "600519.SS": DisruptionAnalysis("600519.SS", "Moutai", -0.05, 0.90, 0.10, 0.02,
        "Baijiu has ultimate brand moat. AI irrelevant to luxury liquor. "
        "But China consumption slowdown is real risk. Not an AI play at all.",
        "China Consumer"),
    "300274.SZ": DisruptionAnalysis("300274.SZ", "Sungrow Power", 0.20, 0.65, 0.50, 0.08,
        "Solar inverter leader. AI helps grid optimization. "
        "Clean energy secular trend regardless of AI. Strong global expansion.",
        "Clean Energy"),
    "601600.SS": DisruptionAnalysis("601600.SS", "Aluminum Corp", 0.10, 0.60, 0.35, 0.05,
        "Aluminum for AI datacenter construction. Counter-intuitive beneficiary. "
        "Commodity cycle play. AI datacenters = more physical infrastructure.",
        "Resources"),
}


class LLMStockAnalyzer:
    """
    Combines quantitative factors with LLM-style disruption analysis.
    Uses pre-computed disruption database (or live LLM calls if API available).
    """

    def __init__(self, disruption_db=None):
        self.db = disruption_db or DISRUPTION_DB

    def get_disruption_factor(self, ticker: str) -> Optional[DisruptionAnalysis]:
        """Get pre-computed disruption analysis for a ticker."""
        return self.db.get(ticker)

    def compute_ai_era_score(self, ticker: str, quant_score: float) -> tuple[float, str]:
        """
        Adjust quantitative score with AI-era disruption factor.
        Returns: (adjusted_score, reasoning)
        """
        analysis = self.get_disruption_factor(ticker)
        if not analysis:
            return quant_score, "No disruption data available"

        # AI-era adjustment
        # Beneficiary boost: up to +0.3
        beneficiary_adj = analysis.ai_beneficiary_score * 0.15

        # Narrative boost: strong narratives create momentum
        narrative_adj = analysis.narrative_score * 0.10

        # Disruption penalty: being disrupted reduces score
        disruption_penalty = -analysis.disruption_risk * 0.20

        # Moat persistence: high moat = more stable
        moat_adj = (analysis.moat_score - 0.5) * 0.05

        total_adj = beneficiary_adj + narrative_adj + disruption_penalty + moat_adj
        adjusted = quant_score + total_adj

        reasoning = (
            f"AI-adj={total_adj:+.3f} | "
            f"Beneficiary={analysis.ai_beneficiary_score:+.2f}({beneficiary_adj:+.3f}) "
            f"Narrative={analysis.narrative_score:+.2f}({narrative_adj:+.3f}) "
            f"Disruption={analysis.disruption_risk:.2f}({disruption_penalty:+.3f}) "
            f"Moat={analysis.moat_score:.2f}({moat_adj:+.3f}) | "
            f"{analysis.sector_theme}: {analysis.reasoning[:80]}"
        )

        return adjusted, reasoning

    def rank_with_disruption(self, quant_rankings: list[dict]) -> list[dict]:
        """Re-rank stocks incorporating AI disruption analysis."""
        enhanced = []
        for item in quant_rankings:
            ticker = item.get("ticker", "")
            quant_score = item.get("score", 0)

            adj_score, reasoning = self.compute_ai_era_score(ticker, quant_score)

            enhanced.append({
                **item,
                "original_score": quant_score,
                "ai_adjusted_score": adj_score,
                "disruption_reasoning": reasoning,
                "score_change": adj_score - quant_score,
            })

        return sorted(enhanced, key=lambda x: x["ai_adjusted_score"], reverse=True)
