"""
文件上传组件，支持多文件上传和自动加载
"""

import os
import tempfile
import streamlit as st
from pathlib import Path

from super_datascope.utils.data_loader import DataLoader


class FileUploader:
    """文件上传组件，支持多文件上传和自动加载"""

    ACCEPTED_EXTENSIONS = list(DataLoader.SUPPORTED_FORMATS.keys())

    def __init__(self, key_prefix: str = "file_upload"):
        self.key_prefix = key_prefix
        # 使用 session_state 持久化临时目录
        temp_dir_key = f"{key_prefix}_temp_dir"
        if temp_dir_key not in st.session_state:
            st.session_state[temp_dir_key] = tempfile.mkdtemp(prefix="super_datascope_")
        self.temp_dir = st.session_state[temp_dir_key]

    def render(self) -> list[dict]:
        """渲染文件上传界面

        Returns:
            list[dict]: 上传的文件信息列表，每项包含:
                - path: 临时文件路径
                - name: 原始文件名
                - size: 文件大小
                - format: 文件格式
        """
        uploaded_files = st.file_uploader(
            "上传数据文件",
            type=[ext.lstrip('.') for ext in self.ACCEPTED_EXTENSIONS],
            accept_multiple_files=True,
            key=f"{self.key_prefix}_uploader",
            help=f"支持格式: {', '.join(self.ACCEPTED_EXTENSIONS)}"
        )

        if not uploaded_files:
            return []

        file_infos = []
        for uploaded_file in uploaded_files:
            # 保存到临时目录
            temp_path = os.path.join(self.temp_dir, uploaded_file.name)
            with open(temp_path, 'wb') as f:
                f.write(uploaded_file.getbuffer())

            info = DataLoader.get_file_info(temp_path)
            file_infos.append(info)

        return file_infos

    def render_uploaded_files_list(self, files: list[dict]):
        """渲染已上传文件列表"""
        if not files:
            return

        st.write(f"**已上传 {len(files)} 个文件:**")
        for f in files:
            ext_icon = {"parquet": "📦", "csv": "📄", "sqlite": "🗃️"}.get(f['format'], "📁")
            st.caption(f"{ext_icon} {f['name']} ({f['size_human']})")
