"""算法仓库管理路由，提供仓库添加、列表、删除等功能"""

from fastapi import APIRouter, HTTPException, status, Depends
from typing import List, Dict, Any, Optional
from pydantic import BaseModel
import uuid

from app.models.models import AlgorithmRepository
from app.models.database import SessionLocal
from app.routes.user import get_current_active_user
from app.gitea.service import gitea_service

router = APIRouter(prefix="/repositories", tags=["repositories"])


class CreateRepositoryRequest(BaseModel):
    """创建仓库请求"""
    name: str
    description: str
    type: str = "code"
    repo_url: str
    branch: str = "main"
    local_path: str = ""
    algorithm_id: Optional[str] = None


class UpdateRepositoryRequest(BaseModel):
    """更新仓库请求"""
    name: Optional[str] = None
    description: Optional[str] = None
    type: Optional[str] = None
    repo_url: Optional[str] = None
    branch: Optional[str] = None
    local_path: Optional[str] = None
    algorithm_id: Optional[str] = None


@router.post("", status_code=status.HTTP_201_CREATED)
async def create_repository(
    request: CreateRepositoryRequest,
    current_user: dict = Depends(get_current_active_user)
):
    """创建算法仓库"""
    # 检查用户权限
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Insufficient permissions")
    
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 生成唯一ID
        repo_id = str(uuid.uuid4())
        
        # 创建仓库实例
        repo = AlgorithmRepository(
            id=repo_id,
            name=request.name,
            description=request.description,
            type=request.type,
            repo_url=request.repo_url,
            branch=request.branch,
            local_path=request.local_path,
            algorithm_id=request.algorithm_id
        )
        
        # 保存到数据库
        db.add(repo)
        db.commit()
        db.refresh(repo)
        
        return {
            "success": True,
            "message": "Repository created successfully",
            "repository": {
                "id": repo.id,
                "name": repo.name,
                "description": repo.description,
                "type": repo.type,
                "repo_url": repo.repo_url,
                "branch": repo.branch,
                "local_path": repo.local_path,
                "algorithm_id": repo.algorithm_id,
                "status": repo.status,
                "created_at": repo.created_at,
                "updated_at": repo.updated_at
            }
        }
    finally:
        db.close()


@router.get("")
async def list_repositories(
    algorithm_id: Optional[str] = None,
    current_user: dict = Depends(get_current_active_user)
):
    """获取算法仓库列表"""
    # 检查用户权限
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Insufficient permissions")
    
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 查询仓库列表
        query = db.query(AlgorithmRepository)
        
        # 如果指定了算法ID，只返回该算法的仓库
        if algorithm_id:
            query = query.filter(AlgorithmRepository.algorithm_id == algorithm_id)
        
        repos = query.all()
        
        # 转换为字典列表
        repo_list = []
        for repo in repos:
            repo_list.append({
                "id": repo.id,
                "name": repo.name,
                "description": repo.description,
                "type": repo.type,
                "repo_url": repo.repo_url,
                "branch": repo.branch,
                "local_path": repo.local_path,
                "algorithm_id": repo.algorithm_id,
                "status": repo.status,
                "created_at": repo.created_at,
                "updated_at": repo.updated_at
            })
        
        return {
            "success": True,
            "repositories": repo_list
        }
    finally:
        db.close()


@router.get("/{repo_id}")
async def get_repository(
    repo_id: str,
    current_user: dict = Depends(get_current_active_user)
):
    """获取单个算法仓库"""
    # 检查用户权限
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Insufficient permissions")
    
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 查询仓库
        repo = db.query(AlgorithmRepository).filter(AlgorithmRepository.id == repo_id).first()
        
        if not repo:
            raise HTTPException(status_code=404, detail="Repository not found")
        
        return {
            "success": True,
            "repository": {
                "id": repo.id,
                "name": repo.name,
                "description": repo.description,
                "type": repo.type,
                "repo_url": repo.repo_url,
                "branch": repo.branch,
                "local_path": repo.local_path,
                "algorithm_id": repo.algorithm_id,
                "status": repo.status,
                "created_at": repo.created_at,
                "updated_at": repo.updated_at
            }
        }
    finally:
        db.close()


@router.put("/{repo_id}")
async def update_repository(
    repo_id: str,
    request: UpdateRepositoryRequest,
    current_user: dict = Depends(get_current_active_user)
):
    """更新算法仓库"""
    # 检查用户权限
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Insufficient permissions")
    
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 查询仓库
        repo = db.query(AlgorithmRepository).filter(AlgorithmRepository.id == repo_id).first()
        
        if not repo:
            raise HTTPException(status_code=404, detail="Repository not found")
        
        # 更新仓库信息
        if request.name is not None:
            repo.name = request.name
        if request.description is not None:
            repo.description = request.description
        if request.type is not None:
            repo.type = request.type
        if request.repo_url is not None:
            repo.repo_url = request.repo_url
        if request.branch is not None:
            repo.branch = request.branch
        if request.local_path is not None:
            repo.local_path = request.local_path
        if request.algorithm_id is not None:
            repo.algorithm_id = request.algorithm_id
        
        # 保存到数据库
        db.commit()
        db.refresh(repo)
        
        return {
            "success": True,
            "message": "Repository updated successfully",
            "repository": {
                "id": repo.id,
                "name": repo.name,
                "description": repo.description,
                "type": repo.type,
                "repo_url": repo.repo_url,
                "branch": repo.branch,
                "local_path": repo.local_path,
                "algorithm_id": repo.algorithm_id,
                "status": repo.status,
                "created_at": repo.created_at,
                "updated_at": repo.updated_at
            }
        }
    finally:
        db.close()


@router.delete("/{repo_id}")
async def delete_repository(
    repo_id: str,
    current_user: dict = Depends(get_current_active_user)
):
    """删除算法仓库"""
    # 检查用户权限
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Insufficient permissions")
    
    # 创建数据库会话
    db = SessionLocal()
    try:
        # 查询仓库
        repo = db.query(AlgorithmRepository).filter(AlgorithmRepository.id == repo_id).first()
        
        if not repo:
            raise HTTPException(status_code=404, detail="Repository not found")
        
        # 先删除Gitea仓库
        gitea_deleted = False
        if repo.repo_url:
            # 从repo_url中提取仓库名称
            import os
            repo_name = os.path.basename(repo.repo_url).replace('.git', '')
            gitea_deleted = gitea_service.delete_repository(repo_name)
            if gitea_deleted:
                print(f"Gitea repository deleted successfully: {repo_name}")
            else:
                print(f"Failed to delete Gitea repository: {repo_name}")
        
        # 删除系统仓库数据
        db.delete(repo)
        db.commit()
        
        return {
            "success": True,
            "message": "Repository deleted successfully",
            "gitea_deleted": gitea_deleted
        }
    finally:
        db.close()
