"""
Super DataScope - 主应用入口
"""

import os
import logging

import streamlit as st

from super_datascope.utils.data_loader import DataLoader, scan_directory
from super_datascope.utils.session_db import SessionDatabase
from super_datascope.components.data_source_manager import DataSourceManager
from super_datascope.views.homepage import homepage_view
from super_datascope.views.data_analysis import data_analysis_view
from super_datascope.views.sql_query import sql_query_view

logger = logging.getLogger("super_datascope")

st.set_page_config(
    page_title="Super DataScope",
    page_icon="📊",
    layout="wide",
    initial_sidebar_state="expanded"
)


def main():
    # 命令行路径自动加载
    input_path = os.environ.get('DATASCOPE_INPUT_PATH', '')
    if input_path and 'cli_loaded' not in st.session_state:
        _load_from_cli(input_path)

    # 没有数据时显示主页
    if 'tables' not in st.session_state or not st.session_state.tables:
        homepage_view()
        return

    # 有数据时显示分析界面
    st.title("📊 Super DataScope")

    with st.sidebar:
        _render_sidebar()

    current_view = st.session_state.get('current_view', '数据洞察')
    if current_view == '数据洞察':
        data_analysis_view()
    elif current_view == 'SQL查询':
        sql_query_view()


def _load_from_cli(input_path: str):
    """从命令行参数加载数据"""
    manager = DataSourceManager()

    if os.path.isdir(input_path):
        file_infos = scan_directory(input_path)
        if file_infos:
            tables = manager.load_files(file_infos)
            _store_tables(tables)
    elif os.path.isfile(input_path):
        info = DataLoader.get_file_info(input_path)
        tables = manager.load_files([info])
        _store_tables(tables)
    else:
        logger.warning(f"命令行路径不存在: {input_path}")

    st.session_state.cli_loaded = True


def _store_tables(tables: dict):
    """将加载的表存入 session_state"""
    if not tables:
        return
    st.session_state.tables = tables
    first_name = list(tables.keys())[0]
    st.session_state.data = tables[first_name]['data']
    st.session_state.current_table_name = first_name


def _render_sidebar():
    """渲染侧边栏"""
    # 功能菜单
    st.header("📋 功能菜单")
    if 'current_view' not in st.session_state:
        st.session_state.current_view = "数据洞察"

    view = st.radio(
        "选择功能",
        options=["数据洞察", "SQL查询"],
        key="view_selector",
        index=0 if st.session_state.current_view == "数据洞察" else 1
    )
    st.session_state.current_view = view

    # 数据表切换
    tables = st.session_state.get('tables', {})
    if tables and len(tables) > 1:
        st.divider()
        st.header("📂 数据表")
        table_names = list(tables.keys())
        current = st.session_state.get('current_table_name', table_names[0])
        idx = table_names.index(current) if current in table_names else 0

        selected = st.selectbox(
            "切换数据表",
            table_names,
            index=idx,
            format_func=lambda n: f"{n} ({tables[n]['data'].shape[0]}行)",
            key="table_selector"
        )
        if selected != st.session_state.get('current_table_name'):
            st.session_state.current_table_name = selected
            st.session_state.data = tables[selected]['data']
            st.rerun()

    elif tables:
        st.divider()
        name = list(tables.keys())[0]
        info = tables[name]
        st.caption(f"📊 {name} — {info['data'].shape[0]} 行 × {info['data'].shape[1]} 列")

    # 会话管理
    _render_session_controls()

    # 返回主页
    st.divider()
    if st.button("🏠 返回主页"):
        for key in ['tables', 'data', 'current_table_name', 'current_config',
                     'cli_loaded', 'current_query', 'query_executed', 'executed_query']:
            st.session_state.pop(key, None)
        st.rerun()


def _render_session_controls():
    """侧边栏会话保存/恢复"""
    st.divider()
    st.header("💾 会话")

    session_db = SessionDatabase()

    # 保存
    with st.expander("保存当前会话"):
        name = st.text_input("会话名称", placeholder="留空自动生成", key="session_save_name")
        if st.button("保存", key="session_save_btn"):
            final_name = name.strip() or session_db.generate_auto_session_name()
            # 收集可序列化的状态
            save_data = {}
            for k in ['current_table_name', 'current_view', 'current_query']:
                if k in st.session_state:
                    save_data[k] = st.session_state[k]
            success, existed = session_db.save_session(final_name, save_data, force_overwrite=True)
            if success:
                st.success(f"已保存: {final_name}")
            else:
                st.error("保存失败")

    # 恢复
    sessions = session_db.get_all_sessions()
    if sessions:
        with st.expander("恢复会话"):
            session_names = [s[0] for s in sessions]
            selected = st.selectbox("选择会话", session_names, key="session_restore_select")
            if st.button("恢复", key="session_restore_btn"):
                data = session_db.load_session(selected)
                if data:
                    for k, v in data.items():
                        st.session_state[k] = v
                    st.success(f"已恢复: {selected}")
                    st.rerun()


if __name__ == "__main__":
    main()
