from typing import List, Optional
from sqlalchemy.orm import Session
from backend.models.database import ProcessingLog


class ProcessingLogService:
    """处理日志服务"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def create(
        self,
        input_type: str,
        content: str,
        customer_id: Optional[int] = None,
        project_id: Optional[int] = None,
        file_path: Optional[str] = None,
        extracted_text: Optional[str] = None,
        dossierai_response: Optional[str] = None,
        issue_type: Optional[str] = None,
        issue_id: Optional[str] = None,
        result: str = 'pending',
        error_message: Optional[str] = None
    ) -> ProcessingLog:
        """创建处理日志"""
        log = ProcessingLog(
            input_type=input_type,
            content=content,
            customer_id=customer_id,
            project_id=project_id,
            file_path=file_path,
            extracted_text=extracted_text,
            dossierai_response=dossierai_response,
            issue_type=issue_type,
            issue_id=issue_id,
            result=result,
            error_message=error_message
        )
        self.db.add(log)
        self.db.commit()
        self.db.refresh(log)
        
        return log
    
    def update(
        self,
        log_id: int,
        **kwargs
    ) -> Optional[ProcessingLog]:
        """更新处理日志"""
        log = self.get_by_id(log_id)
        if not log:
            return None
        
        for key, value in kwargs.items():
            if hasattr(log, key):
                setattr(log, key, value)
        
        self.db.commit()
        self.db.refresh(log)
        
        return log
    
    def get_by_id(self, log_id: int) -> Optional[ProcessingLog]:
        """根据ID获取日志"""
        return self.db.query(ProcessingLog).filter(ProcessingLog.id == log_id).first()
    
    def get_by_project(self, project_id: int) -> List[ProcessingLog]:
        """获取项目的处理日志"""
        return self.db.query(ProcessingLog).filter(
            ProcessingLog.project_id == project_id
        ).order_by(ProcessingLog.created_at.desc()).all()
    
    def get_recent(self, limit: int = 20) -> List[ProcessingLog]:
        """获取最近的处理日志"""
        return self.db.query(ProcessingLog).order_by(
            ProcessingLog.created_at.desc()
        ).limit(limit).all()
    
    def get_pending(self, project_id: int) -> List[ProcessingLog]:
        """获取待同步的处理日志"""
        return self.db.query(ProcessingLog).filter(
            ProcessingLog.project_id == project_id,
            ProcessingLog.result == 'completed',
            ProcessingLog.issue_id.isnot(None)
        ).all()
    
    def mark_synced(self, log_id: int):
        """标记为已同步"""
        log = self.get_by_id(log_id)
        if log:
            log.result = 'synced'
            self.db.commit()
