"""
OCR Validator 文件处理工具（Streamlit 特定）

保留 Streamlit 特定的文件处理函数，通用函数已迁移到 ocr_utils
"""
import os
import cv2
import numpy as np
from typing import Optional, Dict


def load_css_styles(css_path: str = "styles.css") -> str:
    """
    加载CSS样式文件（Streamlit 特定）
    
    Args:
        css_path: CSS 文件路径
        
    Returns:
        CSS 样式内容
    """
    try:
        with open(css_path, 'r', encoding='utf-8') as f:
            return f.read()
    except Exception:
        # 返回基本样式
        return """
        .main > div { background-color: white !important; color: #333333 !important; }
        .stApp { background-color: white !important; }
        .block-container { background-color: white !important; color: #333333 !important; }
        """


def detect_image_orientation_by_opencv(image_path: str) -> Dict:
    """
    使用OpenCV的文本检测来判断图片方向
    
    Args:
        image_path: 图片路径
        
    Returns:
        包含检测结果的字典
    """
    try:
        # 读取图像
        image = cv2.imread(image_path)
        if image is None:
            raise ValueError("无法读取图像文件")
        
        height, width = image.shape[:2]
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        
        # 使用EAST文本检测器或其他方法
        # 这里使用简单的边缘检测和轮廓分析
        edges = cv2.Canny(gray, 50, 150, apertureSize=3)
        
        # 检测直线
        lines = cv2.HoughLines(edges, 1, np.pi/180, threshold=100)
        
        if lines is None:
            return {
                'detected_angle': 0.0,
                'confidence': 0.0,
                'method': 'opencv_analysis',
                'message': '未检测到足够的直线特征'
            }
        
        # 分析直线角度
        angles = []
        for rho, theta in lines[:, 0]:
            angle = theta * 180 / np.pi
            # 将角度标准化到0-180度
            if angle > 90:
                angle = angle - 180
            angles.append(angle)
        
        # 统计主要角度
        angle_hist = np.histogram(angles, bins=36, range=(-90, 90))[0]
        dominant_angle_idx = np.argmax(angle_hist)
        dominant_angle = -90 + dominant_angle_idx * 5  # 每个bin 5度
        
        # 将角度映射到标准旋转角度
        if -22.5 <= dominant_angle <= 22.5:
            detected_angle = 0.0
        elif 22.5 < dominant_angle <= 67.5:
            detected_angle = 270.0
        elif 67.5 < dominant_angle <= 90 or -90 <= dominant_angle < -67.5:
            detected_angle = 90.0
        else:
            detected_angle = 180.0
        
        confidence = angle_hist[dominant_angle_idx] / len(lines) if len(lines) > 0 else 0.0
        
        return {
            'detected_angle': detected_angle,
            'confidence': min(1.0, confidence),
            'method': 'opencv_analysis',
            'line_count': len(lines),
            'dominant_angle': dominant_angle,
            'message': f'基于{len(lines)}条直线检测到旋转角度: {detected_angle}°'
        }
        
    except Exception as e:
        return {
            'detected_angle': 0.0,
            'confidence': 0.0,
            'method': 'opencv_analysis',
            'error': str(e),
            'message': f'OpenCV检测过程中发生错误: {str(e)}'
        }

