"""
主页视图 - 数据源选择与加载
"""

import os
import streamlit as st

from super_datascope.utils.data_loader import DataLoader, scan_directory
from super_datascope.components.file_uploader import FileUploader
from super_datascope.components.data_source_manager import DataSourceManager, render_sqlite_table_selector


def homepage_view():
    """主页视图，提供三种数据接入方式"""

    st.title("📊 Super DataScope")
    st.caption("通用数据集分析工具 — 上传文件或指定路径即可开始分析")

    tab_upload, tab_local, tab_remote = st.tabs([
        "📤 文件上传", "💻 本地路径", "☁️ 远程存储"
    ])

    with tab_upload:
        _render_file_upload_tab()

    with tab_local:
        _render_local_path_tab()

    with tab_remote:
        _render_remote_storage_tab()


def _render_file_upload_tab():
    """文件上传 Tab"""
    st.subheader("上传数据文件")
    st.write("支持 Parquet、CSV、SQLite 格式，可同时上传多个文件。")

    uploader = FileUploader(key_prefix="homepage_upload")
    file_infos = uploader.render()

    if file_infos:
        uploader.render_uploaded_files_list(file_infos)

        # SQLite 文件需要选择表
        for info in file_infos:
            if info['format'] == 'sqlite' and info.get('tables'):
                render_sqlite_table_selector(info['path'], f"upload_{info['name']}")

        if st.button("📊 开始分析", type="primary", key="upload_start"):
            _load_and_enter_analysis(file_infos)


def _render_local_path_tab():
    """本地路径 Tab"""
    st.subheader("从本地路径加载")

    input_path = st.text_input(
        "输入文件或目录路径",
        value=os.environ.get('DATASCOPE_INPUT_PATH', ''),
        placeholder="/path/to/data/ 或 /path/to/file.parquet",
        key="homepage_local_path"
    )

    if not input_path or not input_path.strip():
        st.info("💡 也可以通过命令行启动: `super-datascope /path/to/data/`")
        return

    input_path = input_path.strip()
    file_infos = []

    if os.path.isdir(input_path):
        try:
            file_infos = scan_directory(input_path)
            if file_infos:
                st.success(f"📂 扫描到 {len(file_infos)} 个数据文件")
                for f in file_infos:
                    st.caption(f"  {f['name']} ({f['size_human']})")
            else:
                st.warning("目录中没有找到支持的数据文件")
        except Exception as e:
            st.error(f"扫描目录失败: {e}")
    elif os.path.isfile(input_path):
        try:
            info = DataLoader.get_file_info(input_path)
            st.success(f"📄 {info['name']} ({info['size_human']})")
            file_infos = [info]
        except Exception as e:
            st.error(f"读取文件信息失败: {e}")
    else:
        st.warning("路径不存在，请检查输入")

    if file_infos:
        if st.button("📊 加载并分析", type="primary", key="local_start"):
            _load_and_enter_analysis(file_infos)


def _render_remote_storage_tab():
    """远程存储 Tab（Phase 5 实现）"""
    st.subheader("远程存储")
    st.info("☁️ 远程存储（ObjStorage / MinIO）将在后续版本中支持，敬请期待。")


def _load_and_enter_analysis(file_infos: list[dict]):
    """加载文件并进入分析界面"""
    manager = DataSourceManager()
    tables = manager.load_files(file_infos)

    if not tables:
        st.error("没有成功加载任何数据")
        return

    # 存入 session_state
    st.session_state.tables = tables

    # 单表时同时设置 data 便于兼容
    if len(tables) == 1:
        table_name = list(tables.keys())[0]
        st.session_state.data = tables[table_name]['data']
        st.session_state.current_table_name = table_name
    else:
        # 多表时默认选第一个
        first_name = list(tables.keys())[0]
        st.session_state.data = tables[first_name]['data']
        st.session_state.current_table_name = first_name

    st.rerun()
