"""
目录模式选择器
"""
import streamlit as st
import json
from pathlib import Path
from PIL import Image
from typing import Dict, List

from .config_loader import load_structure_from_config, build_data_source_catalog
from .data_processor import parse_ocr_data, get_structure_from_ocr
from .drawing import clear_table_image_cache


def create_directory_selector(
    data_sources: List[Dict], 
    global_output_config: Dict
) -> str:
    """
    目录模式选择器（优化：避免重复加载）
    
    Args:
        data_sources: 数据源列表
        global_output_config: 全局输出配置
    
    Returns:
        str: 当前模式 ("new" 或 "edit")
    """
    st.sidebar.subheader("目录模式")
    
    source_names = [src["name"] for src in data_sources]
    selected_name = st.sidebar.selectbox(
        "选择数据源", 
        source_names, 
        key="dir_mode_source"
    )
    source_cfg = next(src for src in data_sources if src["name"] == selected_name)
    
    # 🔑 保存当前选择的数据源配置到 session_state
    st.session_state.current_data_source = source_cfg
    
    # 获取输出配置（优先使用数据源自己的 output）
    output_cfg = source_cfg.get("output", global_output_config)
    st.session_state.current_output_config = output_cfg
    
    output_dir = Path(output_cfg.get("directory", "output/table_structures"))
    structure_suffix = output_cfg.get("structure_suffix", "_structure.json")
    
    # 🔑 获取工具类型
    tool = source_cfg.get("tool", "ppstructv3")
    st.session_state.current_tool = tool
    st.sidebar.info(f"🔧 工具: {tool.upper()}")
    
    # 构建/缓存目录清单
    catalog_key = f"catalog::{selected_name}"
    if catalog_key not in st.session_state:
        st.session_state[catalog_key] = build_data_source_catalog(source_cfg)
    catalog = st.session_state[catalog_key]

    if not catalog:
        st.sidebar.warning("目录中没有 JSON 文件")
        return "new"

    # 初始化选择索引
    if 'dir_selected_index' not in st.session_state:
        st.session_state.dir_selected_index = 0

    # 文件选择
    selected = st.sidebar.selectbox(
        "选择文件",
        range(len(catalog)),
        format_func=lambda i: catalog[i]["display"],
        index=st.session_state.dir_selected_index,
        key="dir_select_box"
    )

    # 页码跳转
    page_input = st.sidebar.number_input(
        "页码跳转",
        min_value=1,
        max_value=len(catalog),
        value=catalog[selected]["index"],
        step=1,
        key="dir_page_input"
    )
    
    # 🔑 保存当前选择的目录清单到 session_state（供批量应用使用）
    st.session_state.current_catalog = catalog
    st.session_state.current_catalog_index = selected
    
    # 🔑 关键优化：只在切换文件时才重新加载
    current_entry_key = f"{selected_name}::{catalog[selected]['json']}"
    
    if ('last_loaded_entry' not in st.session_state or 
        st.session_state.last_loaded_entry != current_entry_key):
        
        _load_catalog_entry(
            catalog[selected], 
            output_dir, 
            structure_suffix, 
            current_entry_key,
            tool  # 🔑 传入工具类型
        )
    
    # 页码跳转处理
    if page_input != catalog[selected]["index"]:
        target = next(
            (i for i, item in enumerate(catalog) if item["index"] == page_input), 
            None
        )
        if target is not None:
            st.session_state.dir_selected_index = target
            st.rerun()

    return st.session_state.get('dir_auto_mode', 'new')


def _load_catalog_entry(
    entry: Dict, 
    output_dir: Path, 
    structure_suffix: str, 
    entry_key: str,
    tool: str = "ppstructv3"  # 🔑 新增参数
):
    """
    加载目录条目（JSON + 图片 + 结构）
    
    Args:
        entry: 目录条目
        output_dir: 输出目录
        structure_suffix: 结构文件后缀
        entry_key: 条目唯一键
        tool: 工具类型
    """
    base_name = entry["json"].stem
    structure_file = output_dir / f"{base_name}{structure_suffix}"
    has_structure = structure_file.exists()
    
    # 📂 加载 JSON
    try:
        with open(entry["json"], "r", encoding="utf-8") as fp:
            raw = json.load(fp)
        
        # 🔑 根据工具类型解析数据
        table_bbox, ocr_data = parse_ocr_data(raw, tool)
        
        st.session_state.ocr_data = ocr_data
        st.session_state.table_bbox = table_bbox
        st.session_state.loaded_json_name = entry["json"].name
        st.info(f"🔧 使用 {tool.upper()} 解析 JSON")
        
    except Exception as e:
        st.error(f"❌ 加载 JSON 失败: {e}")
        import traceback
        with st.expander("🔍 详细错误"):
            st.code(traceback.format_exc())
        return

    # 🖼️ 加载图片
    try:
        if entry["image"] and entry["image"].exists():
            st.session_state.image = Image.open(entry["image"])
            st.session_state.loaded_image_name = entry["image"].name
        else:
            st.session_state.image = None
    except Exception as e:
        st.error(f"❌ 加载图片失败: {e}")
        st.session_state.image = None

    # 🎯 自动模式判断
    if has_structure:
        st.session_state.dir_auto_mode = "edit"
        st.session_state.loaded_config_name = structure_file.name
        
        try:
            structure = load_structure_from_config(structure_file)
            st.session_state.structure = structure
            st.session_state.undo_stack = []
            st.session_state.redo_stack = []
            clear_table_image_cache()
            st.sidebar.success("✅ 编辑模式")
        except Exception as e:
            st.error(f"❌ 加载标注失败: {e}")
            st.session_state.dir_auto_mode = "new"
    else:
        st.session_state.dir_auto_mode = "new"
        if 'structure' in st.session_state:
            del st.session_state.structure
        if 'generator' in st.session_state:
            del st.session_state.generator
        st.sidebar.info("🆕 新建模式")
    
    # 标记已加载
    st.session_state.last_loaded_entry = entry_key
    st.info(f"📂 已加载: {entry['json'].name}")