import os
import tempfile
from pathlib import Path
from typing import Optional
from datetime import datetime
from fastapi import APIRouter, UploadFile, File, Form, Depends, HTTPException
from sqlalchemy.orm import Session
from pydantic import BaseModel

from backend.models.database import get_db, init_db
from backend.services.customer_service import CustomerService
from backend.services.project_service import ProjectService
from backend.services.processing_log_service import ProcessingLogService
from backend.services.classifier_service import ClassifierService, IssueType
from backend.services.bug_generator_service import BugGeneratorService
from backend.services.proposal_generator_service import ProposalGeneratorService
from backend.integrations.dossierai_client import get_dossierai_client
from backend.integrations.dossierai_client import DossierAIClient
from backend.services.input_handler import InputHandler

router = APIRouter()


class CustomerCreate(BaseModel):
    name: str
    keywords: Optional[str] = None
    git_repo: Optional[str] = None
    contact: Optional[str] = None


class CustomerUpdate(BaseModel):
    name: Optional[str] = None
    keywords: Optional[str] = None
    git_repo: Optional[str] = None
    contact: Optional[str] = None


class ProjectCreate(BaseModel):
    name: str
    customer_id: Optional[int] = None
    keywords: Optional[str] = None
    git_repo: Optional[str] = None
    oc_collab_enabled: bool = False


class ProjectUpdate(BaseModel):
    name: Optional[str] = None
    customer_id: Optional[int] = None
    keywords: Optional[str] = None
    git_repo: Optional[str] = None
    oc_collab_enabled: Optional[bool] = None


class TextInputRequest(BaseModel):
    text: str
    question: Optional[str] = None


@router.on_event("startup")
async def startup():
    """应用启动时初始化数据库"""
    init_db()


@router.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "ok"}


@router.post("/api/upload")
async def upload_file(
    file: UploadFile = File(...),
    question: Optional[str] = Form(None),
    db: Session = Depends(get_db)
):
    """上传文件处理"""
    # 保存上传的文件
    with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as tmp:
        content = await file.read()
        tmp.write(content)
        tmp_path = tmp.name
    
    try:
        # 初始化服务
        dossierai = get_dossierai_client()
        input_handler = InputHandler(dossierai)
        customer_service = CustomerService(db)
        project_service = ProjectService(db)
        log_service = ProcessingLogService(db)
        classifier = ClassifierService(db)
        
        # 处理文件
        result = await input_handler.process(tmp_path, question)
        
        # 匹配客户和项目
        customer = customer_service.match(result.get('content', ''))
        project = None
        if customer:
            project = project_service.match(result.get('content', ''), customer.id)
        
        # 分类问题
        issue_type, classification = await classifier.classify(result.get('content', ''))
        
        # 保存处理日志
        log = log_service.create(
            input_type=result.get('type', 'unknown'),
            content=result.get('content', ''),
            file_path=tmp_path,
            extracted_text=result.get('extracted_text'),
            dossierai_response=str(result.get('raw_result', {})),
            customer_id=customer.id if customer else None,
            project_id=project.id if project else None,
            result='completed'
        )
        
        return {
            "success": True,
            "data": {
                "result": result,
                "classification": classification,
                "issue_type": issue_type.value
            },
            "customer": {"id": customer.id, "name": customer.name} if customer else None,
            "project": {"id": project.id, "name": project.name} if project else None,
            "log_id": log.id
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        os.unlink(tmp_path)


@router.post("/api/input/text")
async def process_text(
    request: TextInputRequest,
    db: Session = Depends(get_db)
):
    """文本输入处理"""
    try:
        dossierai = get_dossierai_client()
        input_handler = InputHandler(dossierai)
        customer_service = CustomerService(db)
        project_service = ProjectService(db)
        log_service = ProcessingLogService(db)
        classifier = ClassifierService(db)
        
        # 处理文本
        result = await input_handler.process_text(request.text, request.question)
        
        # 匹配客户和项目
        customer = customer_service.match(result.get('content', ''))
        project = None
        if customer:
            project = project_service.match(result.get('content', ''), customer.id)
        
        # 分类问题
        issue_type, classification = await classifier.classify(result.get('content', ''))
        
        # 保存处理日志
        log = log_service.create(
            input_type='text',
            content=request.text,
            extracted_text=result.get('content'),
            customer_id=customer.id if customer else None,
            project_id=project.id if project else None,
            result='completed'
        )
        
        return {
            "success": True,
            "data": {
                "result": result,
                "classification": classification,
                "issue_type": issue_type.value
            },
            "customer": {"id": customer.id, "name": customer.name} if customer else None,
            "project": {"id": project.id, "name": project.name} if project else None,
            "log_id": log.id
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/api/customers")
def list_customers(db: Session = Depends(get_db)):
    """获取客户列表"""
    service = CustomerService(db)
    return service.list_all()


@router.post("/api/customers")
def create_customer(data: CustomerCreate, db: Session = Depends(get_db)):
    """创建客户"""
    service = CustomerService(db)
    customer = service.create(
        name=data.name,
        keywords=data.keywords,
        git_repo=data.git_repo,
        contact=data.contact
    )
    return {
        "id": customer.id,
        "name": customer.name,
        "keywords": customer.keywords,
        "git_repo": customer.git_repo,
        "contact": customer.contact,
        "status": customer.status,
        "created_at": customer.created_at.isoformat() if customer.created_at else None
    }


@router.put("/api/customers/{customer_id}")
def update_customer(customer_id: int, data: CustomerUpdate, db: Session = Depends(get_db)):
    """更新客户"""
    service = CustomerService(db)
    result = service.update(customer_id, **data.model_dump(exclude_unset=True))
    if not result:
        raise HTTPException(status_code=404, detail="Customer not found")
    return {
        "id": result.id,
        "name": result.name,
        "keywords": result.keywords,
        "git_repo": result.git_repo,
        "contact": result.contact,
        "status": result.status,
        "updated_at": result.updated_at.isoformat() if result.updated_at else None
    }


@router.delete("/api/customers/{customer_id}")
def delete_customer(customer_id: int, db: Session = Depends(get_db)):
    """删除客户"""
    service = CustomerService(db)
    if not service.delete(customer_id):
        raise HTTPException(status_code=404, detail="Customer not found")
    return {"success": True}


@router.get("/api/projects")
def list_projects(customer_id: Optional[int] = None, db: Session = Depends(get_db)):
    """获取项目列表"""
    service = ProjectService(db)
    return service.list_all(customer_id=customer_id)


@router.post("/api/projects")
def create_project(data: ProjectCreate, db: Session = Depends(get_db)):
    """创建项目"""
    service = ProjectService(db)
    project = service.create(
        name=data.name,
        customer_id=data.customer_id,
        keywords=data.keywords,
        git_repo=data.git_repo,
        oc_collab_enabled=data.oc_collab_enabled
    )
    return {
        "id": project.id,
        "name": project.name,
        "customer_id": project.customer_id,
        "keywords": project.keywords,
        "git_repo": project.git_repo,
        "status": project.status,
        "progress": project.progress,
        "oc_collab_enabled": project.oc_collab_enabled,
        "created_at": project.created_at.isoformat() if project.created_at else None
    }


@router.get("/api/projects/{project_id}")
def get_project(project_id: int, db: Session = Depends(get_db)):
    """获取项目详情"""
    service = ProjectService(db)
    project = service.get_by_id(project_id)
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    return {
        "id": project.id,
        "name": project.name,
        "customer_id": project.customer_id,
        "keywords": project.keywords,
        "git_repo": project.git_repo,
        "status": project.status,
        "progress": project.progress,
        "oc_collab_enabled": project.oc_collab_enabled,
        "created_at": project.created_at.isoformat() if project.created_at else None,
        "updated_at": project.updated_at.isoformat() if project.updated_at else None
    }


@router.put("/api/projects/{project_id}")
def update_project(project_id: int, data: ProjectUpdate, db: Session = Depends(get_db)):
    """更新项目"""
    service = ProjectService(db)
    result = service.update(project_id, **data.model_dump(exclude_unset=True))
    if not result:
        raise HTTPException(status_code=404, detail="Project not found")
    return {
        "id": result.id,
        "name": result.name,
        "customer_id": result.customer_id,
        "keywords": result.keywords,
        "git_repo": result.git_repo,
        "status": result.status,
        "progress": result.progress,
        "oc_collab_enabled": result.oc_collab_enabled,
        "updated_at": result.updated_at.isoformat() if result.updated_at else None
    }


@router.delete("/api/projects/{project_id}")
def delete_project(project_id: int, db: Session = Depends(get_db)):
    """删除项目"""
    service = ProjectService(db)
    if not service.delete(project_id):
        raise HTTPException(status_code=404, detail="Project not found")
    return {"success": True}


@router.get("/api/logs/recent")
def get_recent_logs(limit: int = 20, db: Session = Depends(get_db)):
    """获取最近处理日志"""
    service = ProcessingLogService(db)
    return service.get_recent(limit)


@router.get("/api/dashboard")
def get_dashboard(db: Session = Depends(get_db)):
    """获取仪表盘数据"""
    project_service = ProjectService(db)
    customer_service = CustomerService(db)
    log_service = ProcessingLogService(db)
    
    projects = project_service.list_all()
    customers = customer_service.list_all()
    recent_logs = log_service.get_recent(10)
    
    return {
        "stats": {
            "totalProjects": len(projects),
            "activeProjects": len([p for p in projects if p.status in ['planning', 'developing', 'testing']]),
            "totalRequirements": 0,
            "totalBugs": 0,
            "resolvedBugs": 0,
            "recentCommits": 0
        },
        "projects": [
            {"name": p.name, "progress": p.progress or 0, "status": p.status}
            for p in projects
        ]
    }


class IssueTypeEnum(str):
    BUG = "bug"
    FEATURE_REQUEST = "feature_request"


@router.get("/api/issues")
def list_issues(type: Optional[str] = None, db: Session = Depends(get_db)):
    """获取问题列表"""
    project_service = ProjectService(db)
    projects = project_service.list_all()
    
    issues = []
    for i, project in enumerate(projects):
        issues.append({
            "id": f"issue-{i+1}",
            "type": IssueTypeEnum.BUG if i % 2 == 0 else IssueTypeEnum.FEATURE_REQUEST,
            "title": f"示例问题 {i+1}",
            "projectName": project.name,
            "status": ["open", "in_progress", "resolved", "closed"][i % 4],
            "severity": ["P0", "P1", "P2", "P3"][i % 4],
            "createdAt": "2024-01-01T00:00:00"
        })
    
    if type:
        issues = [i for i in issues if i["type"] == type]
    
    return issues


class BugCreateRequest(BaseModel):
    material_id: str
    title: str
    severity: str = "P1"
    description: str
    project_id: Optional[int] = None


class ProposalCreateRequest(BaseModel):
    material_id: str
    title: str
    priority: str = "中"
    description: str
    project_id: Optional[int] = None


@router.post("/api/issues/bug")
def create_bug_report(
    data: BugCreateRequest,
    db: Session = Depends(get_db)
):
    """创建BUG报告并保存到Git"""
    from backend.services.git_service import GitService
    from backend.models.database import Material
    
    material = db.query(Material).filter(Material.id == data.material_id).first()
    if not material:
        raise HTTPException(status_code=404, detail="Material not found")
    
    bug_id = f"BUG-{material.id[:8]}"
    
    bug_content = f"""# BUG报告

## 基本信息
- **ID**: {bug_id}
- **标题**: {data.title}
- **严重程度**: {data.severity}
- **项目ID**: {data.project_id}
- **材料**: {material.file_name}
- **创建时间**: {material.created_at.isoformat() if material.created_at else ''}

## 问题描述
{data.description}

## 原始材料
{material.raw_content or '无'}

## 处理结果
{material.processed_content or '无'}

---
*由PM-Agent自动生成*
"""
    
    result = {
        "bug_id": bug_id,
        "content": bug_content,
        "saved_to_git": False,
        "git_path": ""
    }
    
    if data.project_id:
        project_service = ProjectService(db)
        project = project_service.get_by_id(data.project_id)
        if project and project.git_repo:
            try:
                git_service = GitService()
                project_path = str(project.git_repo)
                if not os.path.isabs(project_path):
                    project_path = str(git_service.base_path / project.name)
                
                if os.path.exists(project_path):
                    commit_hash = git_service.create_bug_report(project_path, bug_id, bug_content)
                    result["saved_to_git"] = bool(commit_hash)
                    result["git_path"] = f"{project_path}/docs/00-memos/{bug_id}.md"
            except Exception as e:
                print(f"Git save failed: {e}")
    
    material.issue_type = "bug"
    material.issue_id = bug_id
    material.processed_content = bug_content
    db.commit()
    
    return result


@router.post("/api/issues/proposal")
def create_proposal(
    data: ProposalCreateRequest,
    db: Session = Depends(get_db)
):
    """创建Proposal并保存到Git"""
    from backend.services.git_service import GitService
    from backend.models.database import Material
    
    material = db.query(Material).filter(Material.id == data.material_id).first()
    if not material:
        raise HTTPException(status_code=404, detail="Material not found")
    
    proposal_id = f"REQ-{material.id[:8]}"
    
    proposal_content = f"""# 功能需求Proposal

## 基本信息
- **ID**: {proposal_id}
- **标题**: {data.title}
- **优先级**: {data.priority}
- **项目ID**: {data.project_id}
- **材料**: {material.file_name}
- **创建时间**: {material.created_at.isoformat() if material.created_at else ''}

## 需求描述
{data.description}

## 原始材料
{material.raw_content or '无'}

## 处理结果
{material.processed_content or '无'}

---
*由PM-Agent自动生成*
"""
    
    result = {
        "proposal_id": proposal_id,
        "content": proposal_content,
        "saved_to_git": False,
        "git_path": ""
    }
    
    if data.project_id:
        project_service = ProjectService(db)
        project = project_service.get_by_id(data.project_id)
        if project and project.git_repo:
            try:
                git_service = GitService()
                project_path = str(project.git_repo)
                if not os.path.isabs(project_path):
                    project_path = str(git_service.base_path / project.name)
                
                if os.path.exists(project_path):
                    commit_hash = git_service.create_proposal(project_path, proposal_id, proposal_content)
                    result["saved_to_git"] = bool(commit_hash)
                    result["git_path"] = f"{project_path}/docs/04-proposals/{proposal_id}.md"
            except Exception as e:
                print(f"Git save failed: {e}")
    
    material.issue_type = "feature_request"
    material.issue_id = proposal_id
    material.processed_content = proposal_content
    db.commit()
    
    return result


@router.get("/api/projects/{project_id}/docs")
def get_project_docs(
    project_id: int,
    db: Session = Depends(get_db)
):
    """获取项目开发文档列表"""
    from backend.services.git_service import GitService
    
    project_service = ProjectService(db)
    project = project_service.get_by_id(project_id)
    
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    
    if not project.git_repo:
        return {"documents": [], "message": "项目未配置Git仓库"}
    
    git_service = GitService()
    project_path = str(project.git_repo)
    if not os.path.isabs(project_path):
        project_path = str(git_service.base_path / project.name)
    
    if not os.path.exists(project_path):
        return {"documents": [], "message": "项目仓库未找到"}
    
    try:
        documents = git_service.fetch_development_docs(project_path)
        return {"documents": documents}
    except Exception as e:
        return {"documents": [], "message": str(e)}


@router.get("/api/projects/{project_id}/summary")
def generate_doc_summary(
    project_id: int,
    db: Session = Depends(get_db)
):
    """生成项目开发文档汇总"""
    from backend.services.git_service import GitService
    
    project_service = ProjectService(db)
    project = project_service.get_by_id(project_id)
    
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    
    if not project.git_repo:
        return {"summary": "", "message": "项目未配置Git仓库"}
    
    git_service = GitService()
    project_path = str(project.git_repo)
    if not os.path.isabs(project_path):
        project_path = str(git_service.base_path / project.name)
    
    if not os.path.exists(project_path):
        return {"summary": "", "message": "项目仓库未找到"}
    
    try:
        documents = git_service.fetch_development_docs(project_path)
        
        summary = f"""# {project.name} 开发文档汇总

## 项目信息
- **客户**: {project.customer_id or '未指定'}
- **Git仓库**: {project.git_repo}
- **状态**: {project.status}
- **进度**: {project.progress or 0}%

---

## 文档列表

"""
        
        for doc in documents:
            summary += f"- [{doc['name']}]({doc['relative_path']})\n"
        
        summary += f"""

---
*由PM-Agent自动生成 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""
        
        return {"summary": summary, "document_count": len(documents)}
    except Exception as e:
        return {"summary": "", "message": str(e)}


@router.post("/api/projects/{project_id}/sync-status")
def sync_project_status(
    project_id: int,
    db: Session = Depends(get_db)
):
    """同步项目状态 - 检查Git仓库中的需求和BUG状态"""
    from backend.services.git_service import GitService
    
    project_service = ProjectService(db)
    project = project_service.get_by_id(project_id)
    
    if not project:
        raise HTTPException(status_code=404, detail="Project not found")
    
    if not project.git_repo:
        return {"message": "项目未配置Git仓库", "updated": 0}
    
    git_service = GitService()
    project_path = str(project.git_repo)
    if not os.path.isabs(project_path):
        project_path = str(git_service.base_path / project.name)
    
    if not os.path.exists(project_path):
        return {"message": "项目仓库未找到", "updated": 0}
    
    updated = 0
    
    try:
        req_path = Path(project_path) / "docs" / "01-requirements"
        if req_path.exists():
            for f in req_path.glob("REQ-*.md"):
                content = f.read_text(encoding='utf-8')
                if "状态: 已完成" in content or "status: completed" in content.lower():
                    updated += 1
        
        bug_path = Path(project_path) / "docs" / "00-memos"
        if bug_path.exists():
            for f in bug_path.glob("BUG-*.md"):
                content = f.read_text(encoding='utf-8')
                if "状态: 已修复" in content or "status: resolved" in content.lower():
                    updated += 1
        
        return {
            "message": "状态同步完成",
            "updated": updated,
            "project_id": project_id
        }
    except Exception as e:
        return {"message": str(e), "updated": 0}


@router.get("/api/issues/{issue_id}/status")
def get_issue_status(
    issue_id: str,
    project_id: Optional[int] = None,
    db: Session = Depends(get_db)
):
    """获取问题状态"""
    if project_id:
        from backend.services.git_service import GitService
        
        project_service = ProjectService(db)
        project = project_service.get_by_id(project_id)
        
        if project and project.git_repo:
            git_service = GitService()
            project_path = str(project.git_repo)
            if not os.path.isabs(project_path):
                project_path = str(git_service.base_path / project.name)
            
            if os.path.exists(project_path):
                req_path = Path(project_path) / "docs" / "01-requirements" / f"{issue_id}.md"
                bug_path = Path(project_path) / "docs" / "00-memos" / f"{issue_id}.md"
                
                status = "unknown"
                
                if req_path.exists():
                    content = req_path.read_text(encoding='utf-8')
                    if "状态: 已完成" in content:
                        status = "completed"
                    elif "状态: 进行中" in content:
                        status = "in_progress"
                    else:
                        status = "open"
                elif bug_path.exists():
                    content = bug_path.read_text(encoding='utf-8')
                    if "状态: 已修复" in content:
                        status = "resolved"
                    elif "状态: 进行中" in content:
                        status = "in_progress"
                    else:
                        status = "open"
                
                return {"issue_id": issue_id, "status": status}
    
    return {"issue_id": issue_id, "status": "unknown", "message": "项目未配置Git仓库"}
