"""
VR配置管理器模块

负责VR设置的保存、加载和管理
"""

import os
import json
from pathlib import Path


class VRConfigManager:
    """VR配置管理器类"""

    def __init__(self, config_dir=None):
        """初始化配置管理器

        Args:
            config_dir: 配置目录路径，默认为项目目录/config
        """
        if config_dir is None:
            # 默认使用项目根目录下的config文件夹
            project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            config_dir = os.path.join(project_root, "config")

        self.config_dir = Path(config_dir)
        self.config_file = self.config_dir / "vr_settings.json"

        # 确保配置目录存在
        self.config_dir.mkdir(parents=True, exist_ok=True)

        # 默认配置
        self.default_config = {
            "render_mode": "normal",  # "normal" 或 "render_pipeline"
            "resolution_scale": 0.75,
            "pipeline_resolution_scale": 0.75,
            "quality_preset": "balanced",  # "performance", "balanced", "quality"
            "anti_aliasing": "4x",  # "无", "2x", "4x", "8x"
            "refresh_rate": "90Hz",  # "72Hz", "90Hz", "120Hz", "144Hz"
            "async_reprojection": True,  # 异步重投影开关
            "pipeline_vr_config": {
                "enable_shadows": True,
                "enable_ao": True,
                "enable_bloom": False,
                "enable_motion_blur": False,
                "enable_ssr": False,
                "shadow_quality": "medium",
                "ao_quality": "low"
            }
        }

    def load_config(self):
        """加载VR配置

        Returns:
            dict: VR配置字典
        """
        try:
            if self.config_file.exists():
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                print(f"✓ VR配置已加载: {self.config_file}")
                return config
            else:
                print(f"⚠️ 配置文件不存在，使用默认配置: {self.config_file}")
                return self.default_config.copy()

        except Exception as e:
            print(f"❌ 加载VR配置失败: {e}")
            print("   使用默认配置")
            return self.default_config.copy()

    def save_config(self, config):
        """保存VR配置

        Args:
            config: VR配置字典

        Returns:
            bool: 保存是否成功
        """
        try:
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(config, f, indent=4, ensure_ascii=False)
            print(f"✓ VR配置已保存: {self.config_file}")
            return True

        except Exception as e:
            print(f"❌ 保存VR配置失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def get_render_mode(self):
        """获取渲染模式配置

        Returns:
            str: 渲染模式 ("normal" 或 "render_pipeline")
        """
        config = self.load_config()
        return config.get("render_mode", "normal")

    def set_render_mode(self, mode):
        """设置渲染模式并保存

        Args:
            mode: 渲染模式字符串

        Returns:
            bool: 设置是否成功
        """
        if mode not in ["normal", "render_pipeline"]:
            print(f"❌ 无效的渲染模式: {mode}")
            return False

        config = self.load_config()
        config["render_mode"] = mode
        return self.save_config(config)

    def get_resolution_scale(self):
        """获取分辨率缩放配置

        Returns:
            float: 分辨率缩放系数
        """
        config = self.load_config()
        return config.get("resolution_scale", 0.75)

    def set_resolution_scale(self, scale):
        """设置分辨率缩放并保存

        Args:
            scale: 分辨率缩放系数 (0.5-1.0)

        Returns:
            bool: 设置是否成功
        """
        if not 0.5 <= scale <= 1.0:
            print(f"❌ 无效的分辨率缩放: {scale} (应在0.5-1.0之间)")
            return False

        config = self.load_config()
        config["resolution_scale"] = scale
        return self.save_config(config)

    def get_quality_preset(self):
        """获取质量预设

        Returns:
            str: 质量预设名称
        """
        config = self.load_config()
        return config.get("quality_preset", "balanced")

    def set_quality_preset(self, preset):
        """设置质量预设并保存

        Args:
            preset: 质量预设 ("performance", "balanced", "quality")

        Returns:
            bool: 设置是否成功
        """
        if preset not in ["performance", "balanced", "quality"]:
            print(f"❌ 无效的质量预设: {preset}")
            return False

        config = self.load_config()
        config["quality_preset"] = preset
        return self.save_config(config)

    def get_pipeline_config(self):
        """获取RenderPipeline VR配置

        Returns:
            dict: Pipeline配置字典
        """
        config = self.load_config()
        return config.get("pipeline_vr_config", self.default_config["pipeline_vr_config"].copy())

    def update_pipeline_config(self, pipeline_config):
        """更新RenderPipeline VR配置

        Args:
            pipeline_config: Pipeline配置字典

        Returns:
            bool: 更新是否成功
        """
        config = self.load_config()
        config["pipeline_vr_config"] = pipeline_config
        return self.save_config(config)

    def reset_to_defaults(self):
        """重置为默认配置

        Returns:
            bool: 重置是否成功
        """
        return self.save_config(self.default_config.copy())

    def apply_config_to_vr_manager(self, vr_manager):
        """将配置应用到VR管理器

        Args:
            vr_manager: VRManager实例

        Returns:
            bool: 应用是否成功
        """
        try:
            config = self.load_config()

            # 应用渲染模式
            render_mode = config.get("render_mode", "normal")
            from core.vr import VRRenderMode
            if render_mode == "render_pipeline":
                vr_manager.vr_render_mode = VRRenderMode.RENDER_PIPELINE
            else:
                vr_manager.vr_render_mode = VRRenderMode.NORMAL

            # 应用分辨率缩放
            resolution_scale = config.get("resolution_scale", 0.75)
            vr_manager.resolution_scale = resolution_scale

            # 应用Pipeline分辨率缩放
            pipeline_resolution_scale = config.get("pipeline_resolution_scale", 0.75)
            vr_manager.pipeline_resolution_scale = pipeline_resolution_scale

            # 应用质量预设
            quality_preset = config.get("quality_preset", "balanced")
            vr_manager.current_quality_preset = quality_preset

            # 应用Pipeline配置
            pipeline_config = config.get("pipeline_vr_config", {})
            if pipeline_config:
                vr_manager.pipeline_vr_config.update(pipeline_config)

            print("✓ VR配置已应用到VR管理器")
            return True

        except Exception as e:
            print(f"❌ 应用VR配置失败: {e}")
            import traceback
            traceback.print_exc()
            return False

    def save_from_vr_manager(self, vr_manager):
        """从VR管理器保存当前配置

        Args:
            vr_manager: VRManager实例

        Returns:
            bool: 保存是否成功
        """
        try:
            config = {
                "render_mode": vr_manager.vr_render_mode.value,
                "resolution_scale": vr_manager.resolution_scale,
                "pipeline_resolution_scale": vr_manager.pipeline_resolution_scale,
                "quality_preset": vr_manager.current_quality_preset,
                "pipeline_vr_config": vr_manager.pipeline_vr_config.copy()
            }

            return self.save_config(config)

        except Exception as e:
            print(f"❌ 从VR管理器保存配置失败: {e}")
            import traceback
            traceback.print_exc()
            return False
