"""ST股票列表接口。

获取ST股票列表数据，可根据交易日期获取历史上每天的ST列表。
数据从20160101开始可用，每天上午9:20更新。
"""

import pandas as pd
from typing import Optional

from src.data.client import TushareClient
from src.data.api_wrappers.base_sync import DateBasedSync


def get_stock_st(
    trade_date: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    ts_code: Optional[str] = None,
    client: Optional[TushareClient] = None,
) -> pd.DataFrame:
    """Fetch ST stock list from Tushare.

    This interface retrieves the daily ST stock list including stock codes,
    names, and ST type information. Data is available from 20160101 onwards.
    Updates at 9:20 AM daily.

    Args:
        trade_date: Specific trade date in YYYYMMDD format
        start_date: Start date for date range query (YYYYMMDD format)
        end_date: End date for date range query (YYYYMMDD format)
        ts_code: Stock code filter (optional, e.g., '000001.SZ')
        client: Optional TushareClient instance for shared rate limiting.
                If None, creates a new client. For concurrent sync operations,
                pass a shared client to ensure proper rate limiting.

    Returns:
        pd.DataFrame with columns:
        - ts_code: Stock code
        - name: Stock name
        - trade_date: Trade date (YYYYMMDD)
        - type: Type code
        - type_name: Type name (风险警示板)

    Example:
        >>> # Get all ST stocks for a single date
        >>> data = get_stock_st(trade_date='20240101')
        >>>
        >>> # Get date range data
        >>> data = get_stock_st(start_date='20240101', end_date='20240131')
        >>>
        >>> # Get specific stock ST history
        >>> data = get_stock_st(ts_code='000001.SZ')
    """
    client = client or TushareClient()

    # Build parameters
    params = {}
    if trade_date:
        params["trade_date"] = trade_date
    if start_date:
        params["start_date"] = start_date
    if end_date:
        params["end_date"] = end_date
    if ts_code:
        params["ts_code"] = ts_code

    # Fetch data
    data = client.query("stock_st", **params)

    return data


class StockSTSync(DateBasedSync):
    """ST股票列表批量同步管理器，支持全量/增量同步。

    继承自 DateBasedSync，按日期顺序获取数据。
    数据从 2016 年开始可用，单次请求最大返回1000行数据。

    Example:
        >>> sync = StockSTSync()
        >>> results = sync.sync_all()  # 增量同步
        >>> results = sync.sync_all(force_full=True)  # 全量同步
        >>> preview = sync.preview_sync()  # 预览
    """

    table_name = "stock_st"
    default_start_date = "20160101"

    # 表结构定义
    TABLE_SCHEMA = {
        "ts_code": "VARCHAR(16) NOT NULL",
        "name": "VARCHAR(50)",
        "trade_date": "DATE NOT NULL",
        "type": "VARCHAR(10)",
        "type_name": "VARCHAR(50)",
    }

    # 索引定义
    TABLE_INDEXES = [
        ("idx_stock_st_date_code", ["trade_date", "ts_code"]),
    ]

    # 主键定义
    PRIMARY_KEY = ("trade_date", "ts_code")

    def fetch_single_date(self, trade_date: str) -> pd.DataFrame:
        """获取单日的ST股票列表数据。

        Args:
            trade_date: 交易日期（YYYYMMDD）

        Returns:
            包含当日ST股票列表的 DataFrame
        """
        return get_stock_st(trade_date=trade_date, client=self.client)


def sync_stock_st(
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    force_full: bool = False,
) -> pd.DataFrame:
    """Sync ST stock list to DuckDB with intelligent incremental sync.

    Logic:
    - If table doesn't exist: create table + composite index (trade_date, ts_code) + full sync
    - If table exists: incremental sync from last_date + 1

    Args:
        start_date: Start date for sync (YYYYMMDD format, default: 20160101 for full, last_date+1 for incremental)
        end_date: End date for sync (YYYYMMDD format, default: today)
        force_full: If True, force full reload from 20160101

    Returns:
        pd.DataFrame with synced data
    """
    sync_manager = StockSTSync()
    return sync_manager.sync_all(
        start_date=start_date,
        end_date=end_date,
        force_full=force_full,
    )


if __name__ == "__main__":
    # Test sync
    result = sync_stock_st(end_date="20240102")
    print(f"Synced {len(result)} records")
    if not result.empty:
        print("\nSample data:")
        print(result.head())
