"""
UI组件和页面配置
"""
import streamlit as st
from ocr_validator_file_utils import load_css_styles
from ocr_validator_utils import get_data_source_display_name


def setup_page_config(config):
    """设置页面配置"""
    ui_config = config['ui']
    st.set_page_config(
        page_title=ui_config['page_title'],
        page_icon=ui_config['page_icon'],
        layout=ui_config['layout'],
        initial_sidebar_state=ui_config['sidebar_state']
    )
    
    css_content = load_css_styles()
    st.markdown(f"<style>{css_content}</style>", unsafe_allow_html=True)


def create_data_source_selector(validator):
    """创建双数据源选择器"""
    if not validator.all_sources:
        st.warning("❌ 未找到任何数据源，请检查配置文件")
        return
    
    source_options = {}
    for source_key, source_data in validator.all_sources.items():
        display_name = get_data_source_display_name(source_data['config'])
        source_options[display_name] = source_key
    
    col1, col2 = st.columns(2)
    
    with col1:
        st.markdown("#### 📊 OCR数据源")
        current_display_name = None
        if validator.current_source_key:
            for display_name, key in source_options.items():
                if key == validator.current_source_key:
                    current_display_name = display_name
                    break
        
        selected_ocr_display = st.selectbox(
            "选择OCR数据源",
            options=list(source_options.keys()),
            index=list(source_options.keys()).index(current_display_name) if current_display_name else 0,
            key="ocr_source_selector",
            label_visibility="collapsed",
            help="选择要分析的OCR数据源"
        )
        
        selected_ocr_key = source_options[selected_ocr_display]
        
        if selected_ocr_key != validator.current_source_key:
            validator.switch_to_source(selected_ocr_key)
            if 'selected_file_index' in st.session_state:
                st.session_state.selected_file_index = 0
            # ✅ 数据源变更会在主函数中检测并重置验证结果
            st.rerun()
        
        if validator.current_source_config:
            with st.expander("📋 OCR数据源详情", expanded=False):
                st.write(f"**工具:** {validator.current_source_config['ocr_tool']}")
                st.write(f"**文件数:** {len(validator.file_info)}")
    
    with col2:
        st.markdown("#### 🔍 验证数据源")
        verify_display_name = None
        if validator.verify_source_key:
            for display_name, key in source_options.items():
                if key == validator.verify_source_key:
                    verify_display_name = display_name
                    break
        
        selected_verify_display = st.selectbox(
            "选择验证数据源",
            options=list(source_options.keys()),
            index=list(source_options.keys()).index(verify_display_name) if verify_display_name else (1 if len(source_options) > 1 else 0),
            key="verify_source_selector",
            label_visibility="collapsed",
            help="选择用于交叉验证的数据源"
        )
        
        selected_verify_key = source_options[selected_verify_display]
        
        if selected_verify_key != validator.verify_source_key:
            validator.switch_to_verify_source(selected_verify_key)
            # ✅ 数据源变更会在主函数中检测并重置验证结果
            st.rerun()
        
        if validator.verify_source_config:
            with st.expander("📋 验证数据源详情", expanded=False):
                st.write(f"**工具:** {validator.verify_source_config['ocr_tool']}")
                st.write(f"**文件数:** {len(validator.verify_file_info)}")
    
    # ✅ 显示数据源状态提示
    if validator.current_source_key == validator.verify_source_key:
        st.warning("⚠️ OCR数据源和验证数据源相同，建议选择不同的数据源进行交叉验证")
    else:
        # 检查是否有交叉验证结果
        has_results = 'cross_validation_batch_result' in st.session_state and st.session_state.cross_validation_batch_result is not None
        
        if has_results:
            # 检查验证结果是否与当前数据源匹配
            result = st.session_state.cross_validation_batch_result
            result_ocr_source = result.get('ocr_source', '')
            result_verify_source = result.get('verify_source', '')
            current_ocr_source = get_data_source_display_name(validator.current_source_config)
            current_verify_source = get_data_source_display_name(validator.verify_source_config)
            
            if result_ocr_source == current_ocr_source and result_verify_source == current_verify_source:
                st.success(f"✅ 已选择 {selected_ocr_display} 与 {selected_verify_display} 进行交叉验证（已有验证结果）")
            else:
                st.info(f"ℹ️ 已选择 {selected_ocr_display} 与 {selected_verify_display} 进行交叉验证（验证结果已过期，请重新验证）")
        else:
            st.success(f"✅ 已选择 {selected_ocr_display} 与 {selected_verify_display} 进行交叉验证")


@st.dialog("message", width="small", dismissible=True, on_dismiss="rerun")
def message_box(msg: str, msg_type: str = "info"):
    """消息对话框"""
    if msg_type == "info":
        st.info(msg)
    elif msg_type == "warning":
        st.warning(msg)
    elif msg_type == "error":
        st.error(msg)