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


class ProposalGeneratorService:
    """自动生成Proposal服务"""
    
    def __init__(self, db: Session):
        self.db = db
    
    def generate(
        self, 
        project_id: int, 
        req_info: Dict[str, Any],
        commit_hash: str = None
    ) -> Proposal:
        """生成功能Proposal"""
        proposal_id = self._generate_proposal_id()
        
        proposal = Proposal(
            proposal_id=proposal_id,
            project_id=project_id,
            title=req_info.get('title', '功能需求'),
            background=req_info.get('background', ''),
            user_scenario=req_info.get('user_scenario', ''),
            expected_behavior=req_info.get('expected_behavior', ''),
            priority=req_info.get('priority', 'medium'),
            status='draft',
            estimated_hours=req_info.get('estimated_hours'),
            oc_git_commit_hash=commit_hash,
            created_by='PM-Agent'
        )
        
        self.db.add(proposal)
        self.db.commit()
        self.db.refresh(proposal)
        
        return proposal
    
    def get_by_id(self, proposal_id: str) -> Proposal:
        """根据Proposal ID获取Proposal"""
        return self.db.query(Proposal).filter(Proposal.proposal_id == proposal_id).first()
    
    def get_by_project(self, project_id: int) -> list:
        """获取项目的所有Proposal"""
        return self.db.query(Proposal).filter(Proposal.project_id == project_id).all()
    
    def get_open_proposals(self, project_id: int) -> list:
        """获取项目的未完成Proposal"""
        return self.db.query(Proposal).filter(
            Proposal.project_id == project_id,
            Proposal.status.in_(['draft', 'review', 'approved'])
        ).all()
    
    def update_status(
        self, 
        proposal_id: str, 
        status: str, 
        commit_hash: str = None
    ) -> Proposal:
        """更新Proposal状态"""
        proposal = self.get_by_id(proposal_id)
        if not proposal:
            return None
        
        proposal.status = status
        if commit_hash:
            proposal.oc_git_commit_hash = commit_hash
        if status == 'implemented':
            proposal.implemented_at = datetime.now()
        
        self.db.commit()
        self.db.refresh(proposal)
        
        return proposal
    
    def _generate_proposal_id(self) -> str:
        """生成Proposal ID"""
        from backend.models.database import Proposal
        
        month = datetime.now().strftime('%Y-%m')
        
        # 获取本月的Proposal数量
        count = self.db.query(Proposal).filter(
            Proposal.proposal_id.like(f'PROPOSAL-{month}%')
        ).count()
        
        return f"PROPOSAL-{month}-{str(count + 1).zfill(3)}"
    
    def generate_markdown(self, proposal: Proposal) -> str:
        """生成Proposal Markdown"""
        return f"""# {proposal.title}

**ID**: {proposal.proposal_id}
**提案人**: {proposal.created_by}
**日期**: {proposal.created_at.strftime('%Y-%m-%d') if proposal.created_at else 'N/A'}
**目标版本**: v1.0.0
**状态**: {proposal.status}
**优先级**: {proposal.priority}

---

## 1. 问题背景

{proposal.background or '未提供'}

---

## 2. 用户场景

{proposal.user_scenario or '未提供'}

---

## 3. 期望行为

{proposal.expected_behavior or '未提供'}

---

## 4. 依赖

无

---

## 5. 验收标准

- [ ] 验收项1

---

## 6. 估算工时

{proposal.estimated_hours if proposal.estimated_hours else '待评估'} 小时

---

## 7. 签署确认

| 角色 | 签署人 | 状态 | 日期 |
|------|--------|------|------|
| 产品负责人 | | | |
| 开发负责人 | | | |
| 测试负责人 | | | |
"""
