from datetime import datetime
from typing import Dict, Any
from sqlalchemy.orm import Session
from backend.models.database import Bug


class BugGeneratorService:
    """自动生成BUG报告服务"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def generate(
        self, 
        project_id: int, 
        bug_info: Dict[str, Any],
        commit_hash: str = None
    ) -> Bug:
        """生成BUG报告"""
        bug_id = self._generate_bug_id()
        
        bug = Bug(
            bug_id=bug_id,
            project_id=project_id,
            title=bug_info.get('title', 'BUG'),
            description=bug_info.get('description', ''),
            severity=bug_info.get('severity', 'P2'),
            status='open',
            steps_to_reproduce=','.join(bug_info.get('steps_to_reproduce', [])) if isinstance(bug_info.get('steps_to_reproduce'), list) else bug_info.get('steps_to_reproduce', ''),
            expected_behavior=bug_info.get('expected_behavior', ''),
            actual_behavior=bug_info.get('actual_behavior', ''),
            environment=bug_info.get('environment', ''),
            oc_git_commit_hash=commit_hash,
            created_by='PM-Agent'
        )
        
        self.db.add(bug)
        self.db.commit()
        self.db.refresh(bug)
        
        return bug
    
    def get_by_id(self, bug_id: str) -> Bug:
        """根据BUG ID获取BUG"""
        return self.db.query(Bug).filter(Bug.bug_id == bug_id).first()
    
    def get_by_project(self, project_id: int) -> list:
        """获取项目的所有BUG"""
        return self.db.query(Bug).filter(Bug.project_id == project_id).all()
    
    def get_open_bugs(self, project_id: int) -> list:
        """获取项目的未关闭BUG"""
        return self.db.query(Bug).filter(
            Bug.project_id == project_id,
            Bug.status.in_(['open', 'in_progress'])
        ).all()
    
    def update_status(
        self, 
        bug_id: str, 
        status: str, 
        commit_hash: str = None
    ) -> Bug:
        """更新BUG状态"""
        bug = self.get_by_id(bug_id)
        if not bug:
            return None
        
        bug.status = status
        if commit_hash:
            bug.oc_git_commit_hash = commit_hash
        if status == 'resolved':
            bug.resolved_at = datetime.now()
        
        self.db.commit()
        self.db.refresh(bug)
        
        return bug
    
    def _generate_bug_id(self) -> str:
        """生成BUG ID"""
        from backend.models.database import Bug
        
        today = datetime.now().strftime('%Y%m%d')
        
        # 获取今天的BUG数量
        count = self.db.query(Bug).filter(
            Bug.bug_id.like(f'BUG-{today}%')
        ).count()
        
        return f"BUG-{today}-{str(count + 1).zfill(3)}"
    
    def generate_markdown(self, bug: Bug) -> str:
        """生成BUG报告Markdown"""
        return f"""# Bug报告: {bug.title}

**ID**: {bug.bug_id}
**优先级**: {bug.severity}
**状态**: {bug.status}
**类型**: 功能缺陷
**创建日期**: {bug.created_at.isoformat() if bug.created_at else 'N/A'}
**发现人**: {bug.created_by}

---

## 1. Bug描述

### 1.1 问题陈述

{bug.description or '无'}

---

## 2. 重现步骤

{bug.steps_to_reproduce or '未提供'}

---

## 3. 期望行为

{bug.expected_behavior or '未提供'}

---

## 4. 实际行为

{bug.actual_behavior or '未提供'}

---

## 5. 环境信息

{bug.environment or '未提供'}

---

## 6. 修复记录

| 日期 | 操作 | 负责人 | 备注 |
|------|------|--------|------|
| {bug.created_at.strftime('%Y-%m-%d') if bug.created_at else 'N/A'} | 创建 | {bug.created_by} | 自动生成 |
{f"| {bug.resolved_at.strftime('%Y-%m-%d') if bug.resolved_at else ''} | 修复 | | " if bug.resolved_at else ""}

---

## 7. 验证结果

**验证人**:
**验证日期**:
**验证结果**: ✅ 通过 / ❌ 失败
"""
