from typing import List, Optional
from sqlalchemy.orm import Session
from backend.models.database import Project, Customer, OperationLog


class ProjectService:
    """项目管理服务"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def match(self, content: str, customer_id: Optional[int] = None) -> Optional[Project]:
        """从内容中匹配项目"""
        query = self.db.query(Project).filter(Project.status != 'archived')
        
        if customer_id:
            query = query.filter(Project.customer_id == customer_id)
        
        projects = query.all()
        
        for project in projects:
            if project.keywords:
                keywords = project.keywords.split(',')
                for keyword in keywords:
                    if keyword.strip() and keyword.strip() in content:
                        return project
        
        return None
    
    def get_by_id(self, project_id: int) -> Optional[Project]:
        """根据ID获取项目"""
        return self.db.query(Project).filter(Project.id == project_id).first()
    
    def get_by_name(self, name: str) -> Optional[Project]:
        """根据名称获取项目"""
        return self.db.query(Project).filter(Project.name == name).first()
    
    def create(
        self, 
        name: str, 
        customer_id: Optional[int] = None,
        keywords: Optional[str] = None,
        git_repo: Optional[str] = None,
        **kwargs
    ) -> Project:
        """创建项目"""
        project = Project(
            name=name,
            customer_id=customer_id,
            keywords=keywords,
            git_repo=git_repo,
            status='planning',
            progress=0,
            **kwargs
        )
        self.db.add(project)
        self.db.commit()
        self.db.refresh(project)
        
        self._log_operation('create', 'project', str(project.id), f'创建项目: {name}')
        
        return project
    
    def update(self, project_id: int, **kwargs) -> Optional[Project]:
        """更新项目"""
        project = self.get_by_id(project_id)
        if not project:
            return None
        
        for key, value in kwargs.items():
            if hasattr(project, key):
                setattr(project, key, value)
        
        self.db.commit()
        self.db.refresh(project)
        
        self._log_operation('update', 'project', str(project_id), f'更新项目: {project.name}')
        
        return project
    
    def delete(self, project_id: int) -> bool:
        """删除项目"""
        project = self.get_by_id(project_id)
        if not project:
            return False
        
        project.status = 'archived'
        self.db.commit()
        
        self._log_operation('delete', 'project', str(project_id), f'删除项目: {project.name}')
        
        return True
    
    def list_all(self, customer_id: Optional[int] = None, include_archived: bool = False) -> List[Project]:
        """列出所有项目"""
        query = self.db.query(Project)
        
        if customer_id:
            query = query.filter(Project.customer_id == customer_id)
        
        if not include_archived:
            query = query.filter(Project.status != 'archived')
        
        return query.all()
    
    def update_progress(self, project_id: int, progress: int) -> Optional[Project]:
        """更新项目进度"""
        project = self.get_by_id(project_id)
        if not project:
            return None
        
        project.progress = max(0, min(100, progress))
        self.db.commit()
        self.db.refresh(project)
        
        return project
    
    def update_status(self, project_id: int, status: str) -> Optional[Project]:
        """更新项目状态"""
        project = self.get_by_id(project_id)
        if not project:
            return None
        
        project.status = status
        self.db.commit()
        self.db.refresh(project)
        
        self._log_operation('status_change', 'project', str(project_id), f'状态变更为: {status}')
        
        return project
    
    def _log_operation(self, operation_type: str, target_type: str, target_id: str, details: str):
        """记录操作日志"""
        log = OperationLog(
            operation_type=operation_type,
            target_type=target_type,
            target_id=target_id,
            details=details,
            operator='system'
        )
        self.db.add(log)
        self.db.commit()
