from fastapi import APIRouter, HTTPException, status
from services.preset_service import PresetService

router = APIRouter(prefix="/presets", tags=["presets"])

@router.get("", response_model=dict)
async def list_presets():
	"""获取所有预设列表及其基本信息"""
	try:
		presets = PresetService.list_presets()
		response_data = {"presets": presets}
		print(f"[API] GET /api/presets - 返回数据: {response_data}")
		return response_data
	except Exception as e:
		print(f"[API] GET /api/presets - 错误: {e}")
		import traceback
		traceback.print_exc()
		raise HTTPException(status_code=500, detail=str(e))

# 注意：路由定义顺序很重要！更具体的路由（更多参数）必须放在前面
@router.get("/{preset_name}/components/{component_id}")
async def get_preset_component(preset_name: str, component_id: str):
	"""获取指定组件的详情"""
	raise HTTPException(status_code=501, detail="Not Implemented")

@router.get("/{preset_name}/components")
async def list_preset_components(preset_name: str):
	"""获取预设中的所有组件"""
	raise HTTPException(status_code=501, detail="Not Implemented")

@router.get("/{preset_name}")
async def get_preset(preset_name: str):
	"""获取指定预设的完整内容"""
	try:
		preset_data = PresetService.get_preset(preset_name)
		return preset_data
	except FileNotFoundError:
		raise HTTPException(status_code=404, detail="Preset not found")
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))

@router.post("", status_code=status.HTTP_201_CREATED)
async def create_preset(preset_data: dict):
	"""创建新预设"""
	try:
		preset_name = preset_data.get("name")
		if not preset_name:
			raise HTTPException(status_code=400, detail="preset name is required")
		
		# 使用 create_preset 方法保存预设
		saved_preset = PresetService.create_preset(preset_name, preset_data)
		return {"success": True, "preset": saved_preset}
	except ValueError as e:
		raise HTTPException(status_code=409, detail=str(e))
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))

@router.put("/{preset_name}")
async def update_preset(preset_name: str, update_data: dict):
	"""更新预设配置"""
	try:
		updated_preset = PresetService.update_preset(preset_name, update_data)
		return {"success": True, "preset": updated_preset}
	except FileNotFoundError:
		raise HTTPException(status_code=404, detail="Preset not found")
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))

@router.post("/{preset_name}/rename")
async def rename_preset(preset_name: str, rename_data: dict):
	"""重命名预设（同时修改文件名和内部 name 字段）"""
	try:
		new_name = rename_data.get("newName")
		if not new_name:
			raise HTTPException(status_code=400, detail="newName is required")
		
		# 清理新名称（去掉可能的时间戳和后缀）
		import re
		clean_name = re.sub(r'_\d{10,13}$', '', new_name.replace('.json', ''))
		
		updated_preset = PresetService.rename_preset(preset_name, clean_name)
		return {"success": True, "preset": updated_preset, "newName": clean_name}
	except FileNotFoundError:
		raise HTTPException(status_code=404, detail="Preset not found")
	except ValueError as e:
		raise HTTPException(status_code=409, detail=str(e))
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{preset_name}")
async def delete_preset(preset_name: str):
	"""删除指定预设"""
	try:
		success = PresetService.delete_preset(preset_name)
		if success:
			return {"success": True, "message": f"Preset '{preset_name}' deleted"}
		else:
			raise HTTPException(status_code=404, detail="Preset not found")
	except FileNotFoundError:
		raise HTTPException(status_code=404, detail="Preset not found")
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))

@router.post("/{preset_name}/components", status_code=status.HTTP_201_CREATED)
async def add_preset_component(preset_name: str, component_data: dict):
	"""向预设添加新组件"""
	raise HTTPException(status_code=501, detail="Not Implemented")

@router.put("/{preset_name}/components/{component_id}")
async def update_preset_component(preset_name: str, component_id: str, update_data: dict):
	"""更新指定组件"""
	raise HTTPException(status_code=501, detail="Not Implemented")

@router.delete("/{preset_name}/components/{component_id}")
async def delete_preset_component(preset_name: str, component_id: str):
	"""从预设中删除指定组件"""
	raise HTTPException(status_code=501, detail="Not Implemented")

@router.post("/{preset_name}/reorder")
async def reorder_preset_components(preset_name: str, order_data: dict):
	"""重新排序预设组件"""
	try:
		component_order = order_data.get("component_order", [])
		if not component_order:
			raise HTTPException(status_code=400, detail="component_order is required")
		
		updated_preset = PresetService.reorder_components(preset_name, component_order)
		return {"success": True, "preset": updated_preset}
	except FileNotFoundError:
		raise HTTPException(status_code=404, detail="Preset not found")
	except Exception as e:
		raise HTTPException(status_code=500, detail=str(e))
