from decimal import Decimal
from typing import Any

import requests

from .config import config
from .database import db
from .logger import get_logger


log = get_logger(__name__)


class DeltaApi:
    def __init__(self) -> None:
        self.base = config.delta_api_base.rstrip("/")

    def _get(self, path: str, params: dict | None = None) -> Any:
        url = f"{self.base}{path}"
        try:
            response = requests.get(url, params=params, timeout=15)
            response.raise_for_status()
            db.log_api("delta", path, response.status_code, True, "OK")
            payload = response.json()
            return payload.get("result", payload)
        except Exception as exc:
            db.log_api("delta", path, None, False, str(exc))
            log.exception("Delta REST request failed: %s", path)
            raise

    def products(self) -> list[dict]:
        result = self._get("/v2/products")
        if isinstance(result, dict) and "products" in result:
            return result["products"]
        return result if isinstance(result, list) else []

    def tickers(self) -> list[dict]:
        result = self._get("/v2/tickers")
        if isinstance(result, dict) and "tickers" in result:
            return result["tickers"]
        return result if isinstance(result, list) else []

    def sync_symbols(self) -> int:
        rows = []
        for product in self.products():
            symbol = product.get("symbol")
            if not symbol:
                continue
            max_leverage = int(
                product.get("max_leverage")
                or product.get("max_leverage_notional")
                or product.get("leverage")
                or 1
            )
            rows.append(
                (
                    product.get("id"),
                    symbol,
                    product.get("description") or product.get("underlying_asset", {}).get("symbol"),
                    product.get("contract_type"),
                    product.get("state"),
                    max_leverage,
                    Decimal(str(product.get("tick_size") or 0)),
                    Decimal(str(product.get("contract_value") or product.get("lot_size") or 0)),
                )
            )
        db.execute_many(
            """
            INSERT INTO symbols
              (product_id, symbol, description, contract_type, state, max_leverage, tick_size, lot_size)
            VALUES (%s,%s,%s,%s,%s,%s,%s,%s)
            ON DUPLICATE KEY UPDATE
              product_id = VALUES(product_id),
              description = VALUES(description),
              contract_type = VALUES(contract_type),
              state = VALUES(state),
              max_leverage = VALUES(max_leverage),
              tick_size = VALUES(tick_size),
              lot_size = VALUES(lot_size)
            """,
            rows,
        )
        log.info("Synced %s Delta symbols", len(rows))
        return len(rows)

    def latest_prices(self) -> dict[str, Decimal]:
        prices: dict[str, Decimal] = {}
        for ticker in self.tickers():
            symbol = ticker.get("symbol")
            price = ticker.get("mark_price") or ticker.get("close") or ticker.get("spot_price")
            if symbol and price:
                prices[symbol] = Decimal(str(price))
        return prices


delta_api = DeltaApi()

