"""Batch-download futures historical K-lines by trading day and export to CSV.

Usage:
    export EXSDK_TOKEN="YOUR_TOKEN"
    python export_history_csv.py
"""

import os
import pandas as pd
from exsdk import ExApi

TOKEN = os.environ.get("EXSDK_TOKEN", "YOUR_TOKEN")
SYMBOL = os.environ.get("EXSDK_SYMBOL", "SHFE.au9999")
PERIOD = os.environ.get("EXSDK_PERIOD", "5m")
START_DAY = os.environ.get("EXSDK_START", "20260901")
END_DAY = os.environ.get("EXSDK_END", "20260930")
OUTPUT_FILE = os.environ.get("EXSDK_OUTPUT", "history_klines.csv")


def main() -> None:
    limit = 10000
    cursor = START_DAY
    pages: list[pd.DataFrame] = []

    with ExApi(token=TOKEN) as api:
        while True:
            page = api.tools.download_kline_data(
                symbol=SYMBOL,
                period=PERIOD,
                start=cursor,
                end=END_DAY,
                limit=limit,
            )
            pages.append(page)
            if len(page) < limit:
                break

            # Re-read the last trading day because a full page may truncate it.
            next_day = str(page.iloc[-1]["trading_day"])
            if next_day <= cursor:
                raise RuntimeError(
                    "Daily query limit reached; complete download cannot be guaranteed"
                )
            cursor = next_day

    frame = pd.concat(pages, ignore_index=True)
    if frame.empty:
        print(f"未查询到 {SYMBOL} 在 {START_DAY} 至 {END_DAY} 的 {PERIOD} 历史 K 线。")
        return

    frame = frame.drop_duplicates("timestamp", keep="last").sort_values(
        "timestamp", ignore_index=True
    )
    frame.to_csv(OUTPUT_FILE, index=False, encoding="utf-8-sig")
    print(f"已导出 {len(frame)} 根 {SYMBOL} ({PERIOD}) K 线到 {OUTPUT_FILE}")


if __name__ == "__main__":
    main()
