import os
from pathlib import Path
from dotenv import load_dotenv

# 1. 动态计算项目根目录
# 在 Docker 环境中：config.py 位于 /app/core/，需要向上2级到 /app/
# 在本地开发中：config.py 位于 backend/core/，需要向上3级到项目根目录
_config_path = Path(__file__).resolve()
if _config_path.parent.parent.name == 'app':
    # Docker 环境：/app/core/config.py -> /app/
    PROJECT_ROOT = _config_path.parent.parent
else:
    # 本地开发：backend/core/config.py -> 项目根目录
    PROJECT_ROOT = _config_path.parent.parent.parent

# 2. 加载 .env 文件
# 假设 .env 文件位于项目根目录下
load_dotenv(PROJECT_ROOT / ".env")


class Settings:
	# --- 路径配置 (核心修改) ---

	# 强制使用计算出的项目根目录，不再依赖 .env 中的 BASE_PATH
	BASE_PATH = PROJECT_ROOT

	# 数据目录：固定为根目录下的 data 文件夹
	DATA_PATH = BASE_PATH / "data"

	# --- 核心数据文件路径 ---
	STATE_FILE = DATA_PATH / "state.json"
	SCHEMA_FILE = DATA_PATH / "schema.json"
	PRESETS_FILE = DATA_PATH / "presets.json"
	REGEX_FILE = DATA_PATH / "regex_rules.json"  # 正则规则文件
	SYSTEM_SETTINGS_FILE = DATA_PATH / "system_settings.json"  # 系统设置文件
	VECTORSTORE_PATH = DATA_PATH / "vectorstore"

	# --- 业务数据目录 ---

	# 世界书目录
	WORLDBOOKS_PATH = DATA_PATH / "worldbooks"

	# 预设目录
	PRESET_PATH = DATA_PATH / "preset"

	# 聊天记录目录（同时存放角色卡和聊天）
	CHAT_PATH = DATA_PATH / "chat"
	
	# 兼容别名：用于代码中引用
	CHATS_PATH = CHAT_PATH

	# 临时文件目录
	TEMP_PATH = DATA_PATH / "temp"

	# ComfyUI 工作流目录
	COMFYUI_WORKFLOWS_PATH = DATA_PATH / "comfyui_workflows"
	
	# 角色卡目录（已合并到 CHAT_PATH）
	CHARACTERS_PATH = CHAT_PATH
	
	# 图片资源目录
	IMAGES_PATH = DATA_PATH / "images"

	# Agent 工作流模板与运行记录
	AGENT_TEMPLATES_PATH = DATA_PATH / "agent" / "templates"
	AGENT_RUNS_PATH = DATA_PATH / "agent" / "runs"

	def ensure_directories(self):
		"""确保所有配置的目录存在，如果不存在则创建"""
		directories = [
			self.DATA_PATH,
			self.WORLDBOOKS_PATH,
			self.PRESET_PATH,
			self.CHAT_PATH,
			self.TEMP_PATH,
			self.COMFYUI_WORKFLOWS_PATH,
			self.CHARACTERS_PATH,
			self.IMAGES_PATH,
			self.AGENT_TEMPLATES_PATH,
			self.AGENT_RUNS_PATH,
		]
		for directory in directories:
			directory.mkdir(parents=True, exist_ok=True)
		
		# 确保核心数据文件的父目录存在
		for file_path in [self.STATE_FILE, self.SCHEMA_FILE, self.PRESETS_FILE, self.REGEX_FILE, self.SYSTEM_SETTINGS_FILE]:
			file_path.parent.mkdir(parents=True, exist_ok=True)


settings = Settings()

# 初始化时自动创建必要的目录
settings.ensure_directories()

if __name__ == '__main__':
	settings = Settings()
	print(f"项目根目录: {settings.BASE_PATH}")
	print(f"数据目录: {settings.DATA_PATH}")
	print(f"世界书目录: {settings.WORLDBOOKS_PATH}")
	print(f"预设目录: {settings.PRESETS_PATH}")
	print(f"聊天目录: {settings.CHAT_PATH}")
