"""
Dexorder API - market data and charting for research and trading.

For research scripts, import and use get_api() to access the API:

    from dexorder.api import get_api
    import asyncio

    api = get_api()
    df = asyncio.run(api.data.historical_ohlc(...))
    fig, ax = api.charting.plot_ohlc(df)
"""

import logging
import threading
from typing import Optional

from dexorder.api.api import API
from dexorder.api.charting_api import ChartingAPI
from dexorder.api.data_api import DataAPI

log = logging.getLogger(__name__)

# Global API instance - managed by main.py
_global_api: Optional[API] = None

# Thread-local API — used by harness threads so they don't overwrite the global
_thread_local = threading.local()


def get_api() -> API:
    """
    Get the API instance for accessing market data and charts.

    Use this in research scripts to access the data and charting APIs.

    Returns:
        API instance with data and charting capabilities

    Raises:
        RuntimeError: If called before API initialization (should not happen in research scripts)

    Example:
        from dexorder.api import get_api
        import asyncio

        api = get_api()

        # Fetch data
        df = asyncio.run(api.data.historical_ohlc(
            ticker="BTC/USDT.BINANCE",
            period_seconds=3600,
            start_time="2021-12-20",
            end_time="2021-12-21"
        ))

        # Create chart
        fig, ax = api.charting.plot_ohlc(df, title="BTC/USDT")
    """
    # Thread-local takes priority (set by harness threads)
    api = getattr(_thread_local, 'api', None)
    if api is not None:
        return api
    if _global_api is None:
        raise RuntimeError("API not initialized")
    return _global_api


def set_api(api: API) -> None:
    """Set the API instance.

    When called from the main thread, sets the global API used by all threads.
    When called from a non-main thread (e.g. harness threads), sets a thread-local
    API so the global is not overwritten.
    """
    if threading.current_thread() is threading.main_thread():
        global _global_api
        _global_api = api
    else:
        _thread_local.api = api


__all__ = ['API', 'ChartingAPI', 'DataAPI', 'get_api', 'set_api']
