"""
AkDevz AI Market Intelligence — Data Quality Validator
Performs strict mathematical assertions on market data before analysis.
"""
from typing import List, Dict, Any, Tuple

class DataValidationError(Exception):
    pass

class DataValidator:
    @staticmethod
    def validate_candle(candle: List[Any]) -> Tuple[bool, str]:
        """
        Validates a single candle array: [timestamp, open, high, low, close, volume, (optional oi)]
        """
        if not isinstance(candle, (list, tuple)) or len(candle) < 5:
            return False, "Candle must contain at least timestamp, open, high, low, close"

        ts, o, h, l, c = candle[0], candle[1], candle[2], candle[3], candle[4]
        v = candle[5] if len(candle) > 5 else 0

        try:
            o, h, l, c, v = float(o), float(h), float(l), float(c), float(v)
        except (ValueError, TypeError):
            return False, "OHLCV values must be numeric"

        if o <= 0 or h <= 0 or l <= 0 or c <= 0:
            return False, f"Non-positive price detected: O={o}, H={h}, L={l}, C={c}"

        if h < l:
            return False, f"High ({h}) is less than Low ({l})"

        if h < o or h < c:
            return False, f"High ({h}) is lower than Open ({o}) or Close ({c})"

        if l > o or l > c:
            return False, f"Low ({l}) is higher than Open ({o}) or Close ({c})"

        if v < 0:
            return False, f"Negative volume detected: {v}"

        return True, "OK"

    @staticmethod
    def validate_series(candles: List[List[Any]]) -> Tuple[bool, str]:
        """
        Validates chronological order and individual candles.
        """
        if not candles:
            return False, "Candle series is empty"

        last_ts = -1
        for i, bar in enumerate(candles):
            valid, msg = DataValidator.validate_candle(bar)
            if not valid:
                return False, f"Bar #{i} failed: {msg}"

            ts = bar[0]
            if ts <= last_ts:
                return False, f"Non-monotonic timestamp at bar #{i}: {ts} <= {last_ts}"
            last_ts = ts

        return True, "OK"

    @staticmethod
    def validate_quote(quote: Dict[str, Any], max_age_sec: int = 60) -> Tuple[bool, str]:
        """
        Validates live quote fields and freshness.
        """
        required = ["ltp", "open_price", "high_price", "low_price"]
        for field in required:
            if field not in quote:
                return False, f"Missing required quote field: {field}"

        ltp = float(quote["ltp"])
        if ltp <= 0:
            return False, f"Invalid LTP: {ltp}"

        return True, "OK"
