"""Michael Burry-style deep-value / contrarian scoring.

Burry hunts for statistically cheap, unloved businesses: low multiples on
cash flow and assets, prices near their lows, and Graham "net-net"
tendencies (trading close to or below net current asset value). He wants a
big discount to intangible worth, not growth stories.
"""
from __future__ import annotations

from ..data import StockData
from ..scoring import (Signal, StrategyResult, combine, higher_better,
                       lower_better, verdict_from)


def _pct_above_52w_low(sd: StockData):
    low = sd.get("fiftyTwoWeekLow")
    price = sd.price
    if not low or not price or low == 0:
        return None
    return price / low - 1.0    # 0 = at the low (contrarian sweet spot)


def evaluate(sd: StockData) -> StrategyResult:
    ev_ebitda = sd.get("enterpriseToEbitda")
    pb = sd.get("priceToBook")
    ps = sd.get("priceToSalesTrailing12Months")
    pe = sd.get("trailingPE")
    fcf = sd.get("freeCashflow")
    mcap = sd.market_cap
    fcf_yield = (fcf / mcap) if (fcf and mcap) else None
    above_low = _pct_above_52w_low(sd)

    # Graham net-net proxy: (total cash - total debt) / market cap. Positive and
    # large means a lot of the price is covered by net cash on the books.
    cash = sd.get("totalCash")
    debt = sd.get("totalDebt")
    net_cash_ratio = None
    if cash is not None and debt is not None and mcap:
        net_cash_ratio = (cash - debt) / mcap

    signals = [
        Signal("EV/EBITDA", ev_ebitda, lower_better(ev_ebitda, 4, 14), 0.22),
        Signal("P/B", pb, lower_better(pb, 0.6, 3.0), 0.18, "asset cheapness"),
        Signal("P/S", ps, lower_better(ps, 0.5, 4.0), 0.12),
        Signal("P/E", pe, lower_better(pe, 6, 20), 0.12),
        Signal("FCF_Yield", fcf_yield, higher_better(fcf_yield, 0.03, 0.12), 0.16),
        Signal("AboveLow%", above_low, lower_better(above_low, 0.0, 0.6), 0.12,
               "closeness to 52w low"),
        Signal("NetCash/MCap", net_cash_ratio,
               higher_better(net_cash_ratio, -0.2, 0.3), 0.08, "net-net proxy"),
    ]
    score = combine(signals)
    return StrategyResult("Burry", score, signals, verdict_from(score))
