from backend.modules.database.connection import DatabaseConnection
from backend.modules.database.operations import DatabaseOperations
from backend.modules.database.models import TextRecord, User
from backend.utils.logger_config import setup_logger
from typing import Optional, List, Dict, Any
import os


logger = setup_logger(__name__)

"""
实现用户文本模板管理服务：用户创建、编辑、删除、查找文本模板
"""

class UserTemplateService:
    def __init__(self):
        self.db_ops = DatabaseOperations()

    def create_text_template(self, user_id: int, text_type: str, text_name: str, text_label: str, text_content: str) -> dict:
        """
        创建文本模板
        """
        logger.info(f"用户{user_id}创建文本模板: {text_name}, 类型: {text_type}")
        user = self.db_ops.get_user_by_id(user_id)
        if not user:
            return {"success": False, "error": "用户不存在"}
        
        text_record = self.db_ops.create_text_record(
            user_id=user_id,
            text_type=text_type,
            text_name=text_name,
            text_label=text_label,
            text_content=text_content
        )
        if not text_record:
            return {"success": False, "error": "数据库记录失败"}

        return {
            "success": True,
            "text_id": text_record['id'],
            "text_name": text_name,
            "text_label": text_label,
            "text_content": text_content
        }

    def list_text_templates(self, user_id: int, text_type: Optional[str] = None, page: int = 1, page_size: int = 20) -> dict:
        """
        获取用户文本模板列表
        """
        logger.info(f"获取用户{user_id}的文本模板列表, 类型: {text_type}, 页码: {page}")
        user = self.db_ops.get_user_by_id(user_id)
        if not user:
            return {"success": False, "error": "用户不存在"}
        
        result = self.db_ops.get_user_text_records(user_id, text_type, page, page_size)
        return {
            "success": True,
            "templates": result.get("records", []),
            "total": result.get("total", 0),
            "page": result.get("page", 1),
            "page_size": result.get("page_size", 20),
            "total_pages": result.get("total_pages", 1)
        }

    def delete_text_template(self, user_id: int, text_id: int) -> dict:
        """
        删除文本模板
        """
        logger.info(f"用户{user_id}删除文本模板: {text_id}")
        user = self.db_ops.get_user_by_id(user_id)
        if not user:
            return {"success": False, "error": "用户不存在"}
        
        text_record = self.db_ops.get_text_record_by_id(text_id)
        if not text_record:
            return {"success": False, "error": "文本模板不存在"}
        if text_record['user_id'] != user_id:
            return {"success": False, "error": "无权删除他人模板"}
        success = self.db_ops.delete_text_record(text_id)
        if not success:
            return {"success": False, "error": "文本模板删除失败"}
        return {"success": True, "message": "文本模板删除成功"}
    
    def update_text_template(self, user_id: int, text_id: int, data: dict) -> Dict[str, Any]:
        """
        更新文本模板
        """
        logger.info(f"用户{user_id}更新文本模板: {text_id}")
        user = self.db_ops.get_user_by_id(user_id)
        if not user:
            return {"success": False, "error": "用户不存在"}
        
        text_record = self.db_ops.get_text_record_by_id(text_id)
        if not text_record:
            return {"success": False, "error": "文本模板不存在"}
        if text_record['user_id'] != user_id:
            return {"success": False, "error": "无权更新他人模板"}
        success = self.db_ops.update_text_record(text_id, **data)
        if not success:
            return {"success": False, "error": "数据库更新失败"}
        return {"success": True, "message": "文本模板更新成功"}

user_template_service = UserTemplateService()