"""
K线图表组件

基于lightweight-charts的K线图表
"""

import pandas as pd
from lightweight_charts import Chart
from datetime import datetime


class KlineChart:
    """K线图表类"""

    def __init__(self, title: str = "K线图", toolbox: bool = True):
        self.title = title
        self.toolbox = toolbox
        self.chart = None
        self.subcharts = {}

    def create(self, maximize: bool = True) -> Chart:
        """创建图表实例"""
        self.chart = Chart(toolbox=self.toolbox, inner_height=0.8, maximize=maximize)
        self.chart.layout(font_family="Times New Roman")
        self.chart.legend(visible=True, font_size=14, color="#FFFFFF")
        return self.chart

    def set_data(self, df: pd.DataFrame, time_col: str = "time"):
        """设置K线数据"""
        if self.chart is None:
            self.create()

        # 验证数据
        required_cols = ["open", "high", "low", "close", "volume"]
        missing = [c for c in required_cols if c not in df.columns]
        if missing:
            raise ValueError(f"缺少必要列: {missing}")

        # 确保时间列格式正确
        df = df.copy()
        if time_col in df.columns:
            df[time_col] = pd.to_datetime(df[time_col])

        self.chart.set(df)

    def set_visible_range(self, start_time: datetime, end_time: datetime):
        """设置可见范围"""
        if self.chart:
            self.chart.set_visible_range(start_time, end_time)

    def add_topbar_text(self, key: str, text: str):
        """添加顶部栏文本"""
        if self.chart:
            self.chart.topbar.textbox(key, text)

    def show(self, block: bool = True):
        """显示图表"""
        if self.chart:
            self.chart.show(block=block)


def create_kline_chart(
    df: pd.DataFrame,
    symbol: str,
    name: str,
    timeframe: str,
    init_visible_bars: int = 90,
) -> Chart:
    """
    快速创建K线图表

    Args:
        df: DataFrame with OHLCV data
        symbol: 标的代码
        name: 标的名称
        timeframe: 时间周期
        init_visible_bars: 初始可见K线数量

    Returns:
        Chart实例
    """
    chart = KlineChart()
    chart.create(maximize=True)

    chart.add_topbar_text("symbol", symbol)
    chart.add_topbar_text("name", name)
    chart.add_topbar_text("timeframe", timeframe)

    chart.set_data(df)

    # 设置初始可见范围
    if len(df) > init_visible_bars:
        end_time = df["time"].iloc[-1]
        start_time = df["time"].iloc[-init_visible_bars]
        chart.set_visible_range(start_time, end_time)

    return chart.chart
