"""
AkDevz AI Market Intelligence — Real-time Market Data Collector
Collects realtime quotes, validates timestamp freshness, and enforces chunking of 50 symbols.
"""
import time
from typing import List, Dict, Any, Optional
from datetime import datetime
from zoneinfo import ZoneInfo

from python.fyers.rest_client import FyersRestClient
from python.config.settings import settings

IST = ZoneInfo("Asia/Kolkata")

class RealtimeCollector:
    MAX_SYMBOLS_PER_BATCH = 50  # FYERS Standard Limit

    def __init__(self, rest_client: Optional[FyersRestClient] = None):
        self.client = rest_client or FyersRestClient()
        self.freshness_threshold_sec = settings.data_freshness_intraday_max_age_sec

    def collect_quotes(self, symbols: List[str]) -> Dict[str, Any]:
        """
        Batches symbol list into groups of 50 and queries FYERS quotes API.
        Annotates freshness status and validation checks.
        """
        if not symbols:
            return {}

        raw_quotes = self.client.get_quotes(symbols)
        results = {}
        now_ts = int(time.time())

        for sym in symbols:
            q = raw_quotes.get(sym)
            if not q:
                results[sym] = {
                    "symbol": sym,
                    "status": "UNAVAILABLE",
                    "ltp": None,
                    "freshness": "NO_DATA",
                    "age_sec": None,
                }
                continue

            quote_time = q.get("tt", now_ts)
            age_sec = max(0, now_ts - quote_time)
            is_stale = age_sec > self.freshness_threshold_sec

            results[sym] = {
                "symbol": sym,
                "status": "VALID",
                "ltp": float(q.get("lp", 0.0)),
                "open": float(q.get("open_price", 0.0)),
                "high": float(q.get("high_price", 0.0)),
                "low": float(q.get("low_price", 0.0)),
                "prev_close": float(q.get("prev_close_price", 0.0)),
                "volume": int(q.get("volume", 0)),
                "change": float(q.get("ch", 0.0)),
                "change_pct": float(q.get("chp", 0.0)),
                "bid": float(q.get("bid", 0.0)),
                "ask": float(q.get("ask", 0.0)),
                "timestamp": quote_time,
                "age_sec": age_sec,
                "freshness": "STALE" if is_stale else "LIVE",
                "source": "FYERS_API_V3"
            }

        return results
