"""Pybit HTTP session factory."""

import json
import os

from pybit.unified_trading import HTTP

from bybit_mcp_server.config import get_api_key, get_api_secret, get_db_path, get_recv_window, get_testnet


def get_session() -> HTTP:
    """Create a new pybit HTTP session.

    Credential resolution order:
    1. SQLite database (if exists and has credentials) — for remote/auth mode
    2. Environment variables — for stdio/local mode (backward compatible)
    """
    db_path = get_db_path()
    if db_path and os.path.exists(db_path):
        try:
            from bybit_mcp_server.auth.db import load_bybit_credentials

            creds = load_bybit_credentials(db_path)
            if creds and creds.get("api_key") and creds.get("api_secret"):
                kwargs: dict = {
                    "testnet": creds["testnet"],
                    "api_key": creds["api_key"],
                    "api_secret": creds["api_secret"],
                }
                if creds.get("recv_window") is not None:
                    kwargs["recv_window"] = creds["recv_window"]
                return HTTP(**kwargs)
        except Exception:
            pass  # Fall through to env vars

    # Fallback: environment variables
    kwargs = {
        "testnet": get_testnet(),
        "api_key": get_api_key(),
        "api_secret": get_api_secret(),
    }
    recv_window = get_recv_window()
    if recv_window is not None:
        kwargs["recv_window"] = recv_window
    return HTTP(**kwargs)


def format_result(result: dict) -> str:
    """Extract the 'result' key from pybit response and format as JSON string."""
    return json.dumps(result["result"], indent=2)
