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


class CustomerService:
    """客户管理服务"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def match(self, content: str) -> Optional[Customer]:
        """从内容中匹配客户"""
        customers = self.db.query(Customer).filter(Customer.status == 'active').all()
        
        for customer in customers:
            if customer.keywords:
                keywords = customer.keywords.split(',')
                for keyword in keywords:
                    if keyword.strip() and keyword.strip() in content:
                        return customer
        
        return None
    
    def get_by_id(self, customer_id: int) -> Optional[Customer]:
        """根据ID获取客户"""
        return self.db.query(Customer).filter(Customer.id == customer_id).first()
    
    def get_by_name(self, name: str) -> Optional[Customer]:
        """根据名称获取客户"""
        return self.db.query(Customer).filter(Customer.name == name).first()
    
    def create(
        self, 
        name: str, 
        keywords: Optional[str] = None, 
        git_repo: Optional[str] = None, 
        contact: Optional[str] = None
    ) -> Customer:
        """创建客户"""
        customer = Customer(
            name=name,
            keywords=keywords,
            git_repo=git_repo,
            contact=contact
        )
        self.db.add(customer)
        self.db.commit()
        self.db.refresh(customer)
        
        self._log_operation('create', 'customer', str(customer.id), f'创建客户: {name}')
        
        return customer
    
    def update(self, customer_id: int, **kwargs) -> Optional[Customer]:
        """更新客户"""
        customer = self.get_by_id(customer_id)
        if not customer:
            return None
        
        for key, value in kwargs.items():
            if hasattr(customer, key):
                setattr(customer, key, value)
        
        self.db.commit()
        self.db.refresh(customer)
        
        self._log_operation('update', 'customer', str(customer_id), f'更新客户: {customer.name}')
        
        return customer
    
    def delete(self, customer_id: int) -> bool:
        """删除客户"""
        customer = self.get_by_id(customer_id)
        if not customer:
            return False
        
        customer.status = 'inactive'
        self.db.commit()
        
        self._log_operation('delete', 'customer', str(customer_id), f'删除客户: {customer.name}')
        
        return True
    
    def list_all(self, include_inactive: bool = False) -> List[Customer]:
        """列出所有客户"""
        query = self.db.query(Customer)
        if not include_inactive:
            query = query.filter(Customer.status == 'active')
        return query.all()
    
    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()
