#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Web端朝向检测器
提供Web API接口用于获取GPS位置和设备朝向信息
"""

from flask import Blueprint, jsonify, request
import json
import time
from typing import Dict, Optional, Tuple
from . import config
from .orientation_detector import OrientationDetector


class WebOrientationDetector:
    """Web端朝向检测器"""
    
    def __init__(self):
        self.orientation_detector = OrientationDetector()
        self.current_web_location = None
        self.current_web_heading = None
        self.last_web_update = 0
        
        # 创建Blueprint
        self.blueprint = Blueprint('orientation', __name__)
        self.setup_routes()
    
    def setup_routes(self):
        """设置Web API路由"""
        
        @self.blueprint.route('/api/orientation/auto_configure', methods=['POST'])
        def auto_configure_from_web():
            """从Web端自动配置摄像头位置和朝向"""
            try:
                data = request.get_json() or {}
                print(f"🔍 收到自动配置请求: {data}")
                
                # 支持两种数据格式
                # 新格式: {gps_location: [lat, lng], user_heading: heading, apply_config: true}
                # 旧格式: {gps: {...}, orientation: {...}}
                
                if 'gps_location' in data:
                    # 新格式处理
                    gps_location = data.get('gps_location')
                    user_heading = data.get('user_heading', 0)
                    apply_config = data.get('apply_config', True)
                    
                    if not gps_location or len(gps_location) < 2:
                        return jsonify({
                            "success": False,
                            "error": "GPS位置数据格式错误"
                        })
                    
                    lat, lng = float(gps_location[0]), float(gps_location[1])
                    
                    # 验证坐标范围
                    if not (-90 <= lat <= 90) or not (-180 <= lng <= 180):
                        return jsonify({
                            "success": False,
                            "error": "GPS坐标范围不正确"
                        })
                    
                    # 计算摄像头朝向
                    if user_heading is not None:
                        # 计算摄像头朝向（朝向用户方向）
                        camera_heading = (user_heading + 180) % 360
                    else:
                        camera_heading = 0.0
                    
                    print(f"📍 处理GPS位置: ({lat:.6f}, {lng:.6f})")
                    print(f"🧭 用户朝向: {user_heading}°, 摄像头朝向: {camera_heading}°")
                    
                    if apply_config:
                        # 应用配置
                        self.orientation_detector.update_camera_config((lat, lng), camera_heading)
                        print(f"✅ 配置已应用到系统")
                    
                    return jsonify({
                        "success": True,
                        "message": "摄像头位置和朝向已自动配置",
                        "gps_location": [lat, lng],
                        "user_heading": user_heading,
                        "camera_heading": camera_heading,
                        "applied": apply_config
                    })
                
                else:
                    # 旧格式处理
                    gps_data = data.get('gps')
                    orientation_data = data.get('orientation')
                    
                    if not gps_data:
                        # 如果前端没有提供GPS，尝试后端获取
                        result = self.orientation_detector.auto_configure_camera_location()
                    else:
                        # 使用前端提供的数据
                        result = self.process_web_data(gps_data, orientation_data)
                    
                    if result['success']:
                        # 应用配置
                        self.orientation_detector.update_camera_config(
                            result['gps_location'], 
                            result['camera_heading']
                        )
                        
                        return jsonify({
                            "success": True,
                            "message": "摄像头位置和朝向已自动配置",
                            **result
                        })
                    else:
                        return jsonify({
                            "success": False,
                            "error": result.get('error', '自动配置失败')
                        })
                    
            except Exception as e:
                print(f"❌ 自动配置异常: {e}")
                import traceback
                traceback.print_exc()
                return jsonify({
                    "success": False,
                    "error": f"配置失败: {str(e)}"
                })
        
        @self.blueprint.route('/api/orientation/update_location', methods=['POST'])
        def update_location():
            """更新GPS位置信息"""
            try:
                data = request.get_json()
                
                if not data or 'latitude' not in data or 'longitude' not in data:
                    return jsonify({
                        "status": "error",
                        "message": "缺少位置信息"
                    })
                
                lat = float(data['latitude'])
                lng = float(data['longitude'])
                accuracy = float(data.get('accuracy', 1000))
                
                # 验证坐标范围
                if not (-90 <= lat <= 90) or not (-180 <= lng <= 180):
                    return jsonify({
                        "status": "error",
                        "message": "坐标范围不正确"
                    })
                
                # 更新位置信息
                self.current_web_location = (lat, lng, accuracy)
                self.last_web_update = time.time()
                
                print(f"📍 Web GPS更新: ({lat:.6f}, {lng:.6f}), 精度: ±{accuracy:.0f}m")
                
                return jsonify({
                    "status": "success",
                    "message": "位置信息已更新"
                })
                
            except Exception as e:
                return jsonify({
                    "status": "error",
                    "message": f"位置更新失败: {str(e)}"
                })
        
        @self.blueprint.route('/api/orientation/update_heading', methods=['POST'])
        def update_heading():
            """更新设备朝向信息"""
            try:
                data = request.get_json()
                
                if not data or 'heading' not in data:
                    return jsonify({
                        "status": "error",
                        "message": "缺少朝向信息"
                    })
                
                heading = float(data['heading'])
                
                # 标准化角度到0-360范围
                heading = heading % 360
                
                # 更新朝向信息
                self.current_web_heading = heading
                self.last_web_update = time.time()
                
                print(f"🧭 Web朝向更新: {heading:.1f}°")
                
                return jsonify({
                    "status": "success",
                    "message": "朝向信息已更新"
                })
                
            except Exception as e:
                return jsonify({
                    "status": "error",
                    "message": f"朝向更新失败: {str(e)}"
                })
        
        @self.blueprint.route('/api/orientation/get_status')
        def get_orientation_status():
            """获取当前朝向状态"""
            try:
                current_time = time.time()
                
                # 检查数据是否过期（30秒）
                web_data_fresh = (current_time - self.last_web_update) < 30
                
                status = {
                    "web_location": self.current_web_location,
                    "web_heading": self.current_web_heading,
                    "web_data_fresh": web_data_fresh,
                    "last_update": self.last_web_update,
                    "current_config": {
                        "latitude": config.CAMERA_LATITUDE,
                        "longitude": config.CAMERA_LONGITUDE,
                        "heading": config.CAMERA_HEADING
                    }
                }
                
                return jsonify({
                    "status": "success",
                    "data": status
                })
                
            except Exception as e:
                return jsonify({
                    "status": "error",
                    "message": f"状态获取失败: {str(e)}"
                })
        
        @self.blueprint.route('/api/orientation/apply_config', methods=['POST'])
        def apply_config():
            """应用当前的位置和朝向配置"""
            try:
                if not self.current_web_location:
                    return jsonify({
                        "status": "error",
                        "message": "没有可用的位置信息"
                    })
                
                lat, lng, accuracy = self.current_web_location
                
                # 使用Web朝向或默认朝向
                if self.current_web_heading is not None:
                    # 计算摄像头朝向（朝向用户）
                    camera_heading = self.orientation_detector.calculate_camera_heading_facing_user(
                        self.current_web_heading
                    )
                else:
                    # 使用默认朝向
                    camera_heading = 0.0
                
                # 应用配置
                self.orientation_detector.update_camera_config((lat, lng), camera_heading)
                
                return jsonify({
                    "status": "success",
                    "message": "配置已应用",
                    "data": {
                        "latitude": lat,
                        "longitude": lng,
                        "camera_heading": camera_heading,
                        "accuracy": accuracy
                    }
                })
                
            except Exception as e:
                return jsonify({
                    "status": "error",
                    "message": f"配置应用失败: {str(e)}"
                })
    
    def process_web_data(self, gps_data: Dict, orientation_data: Optional[Dict] = None) -> Dict:
        """
        处理来自Web端的GPS和朝向数据
        
        Args:
            gps_data: GPS数据 {'latitude': float, 'longitude': float, 'accuracy': float}
            orientation_data: 朝向数据 {'heading': float} (可选)
            
        Returns:
            配置结果字典
        """
        result = {
            'success': False,
            'gps_location': None,
            'device_heading': None,
            'camera_heading': None,
            'method': 'Web',
            'accuracy': None
        }
        
        try:
            # 处理GPS数据
            lat = float(gps_data['latitude'])
            lng = float(gps_data['longitude'])
            accuracy = float(gps_data.get('accuracy', 1000))
            
            # 验证坐标
            if not (-90 <= lat <= 90) or not (-180 <= lng <= 180):
                raise ValueError("坐标范围不正确")
            
            result['gps_location'] = (lat, lng)
            result['accuracy'] = accuracy
            
            # 处理朝向数据
            device_heading = 0.0  # 默认朝向
            if orientation_data and 'heading' in orientation_data:
                device_heading = float(orientation_data['heading']) % 360
            
            result['device_heading'] = device_heading
            
            # 计算摄像头朝向（面向用户）
            camera_heading = self.orientation_detector.calculate_camera_heading_facing_user(device_heading)
            result['camera_heading'] = camera_heading
            
            result['success'] = True
            
            print(f"✅ Web数据处理完成:")
            print(f"📍 GPS位置: ({lat:.6f}, {lng:.6f})")
            print(f"🧭 设备朝向: {device_heading:.1f}°")
            print(f"📷 摄像头朝向: {camera_heading:.1f}°")
            print(f"📏 定位精度: ±{accuracy:.0f}m")
            
        except Exception as e:
            print(f"❌ Web数据处理失败: {e}")
        
        return result
    
    def get_blueprint(self):
        """获取Flask Blueprint"""
        return self.blueprint 