"""Gitea integration endpoints."""
from typing import List, Dict, Any
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.core.database import get_db
from app.models.integration import Integration, IntegrationType
from app.models.organization import OrganizationMember
from app.api.deps import require_role
from app.services.gitea import GiteaService

router = APIRouter()

@router.get("/repos", response_model=List[Dict[str, Any]])
async def list_repositories(
    org_id: int,
    member: OrganizationMember = Depends(require_role("viewer")),
    db: AsyncSession = Depends(get_db)
):
    """List Gitea repositories for organization."""
    # Get Gitea integration
    result = await db.execute(
        select(Integration)
        .where(Integration.organization_id == org_id)
        .where(Integration.type == IntegrationType.GITLAB)  # Using GITLAB as Gitea
        .where(Integration.status == "ACTIVE")
    )
    integration = result.scalar_one_or_none()
    
    if not integration or not integration.base_url or not integration.api_key:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Gitea integration not configured"
        )
    
    gitea = GiteaService(integration.base_url, integration.api_key)
    repos = await gitea.list_repositories("startdata")  # Fixed owner for now
    
    return repos

@router.get("/repos/{owner}/{repo}")
async def get_repository(
    org_id: int,
    owner: str,
    repo: str,
    member: OrganizationMember = Depends(require_role("viewer")),
    db: AsyncSession = Depends(get_db)
):
    """Get repository details."""
    result = await db.execute(
        select(Integration)
        .where(Integration.organization_id == org_id)
        .where(Integration.type == IntegrationType.GITLAB)
        .where(Integration.status == "ACTIVE")
    )
    integration = result.scalar_one_or_none()
    
    if not integration or not integration.base_url or not integration.api_key:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Gitea integration not configured"
        )
    
    gitea = GiteaService(integration.base_url, integration.api_key)
    repo_data = await gitea.get_repo(owner, repo)
    
    if not repo_data:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Repository not found"
        )
    
    return repo_data

@router.get("/repos/{owner}/{repo}/file")
async def get_file(
    org_id: int,
    owner: str,
    repo: str,
    path: str,
    ref: str = "main",
    member: OrganizationMember = Depends(require_role("viewer")),
    db: AsyncSession = Depends(get_db)
):
    """Get file content from repository."""
    result = await db.execute(
        select(Integration)
        .where(Integration.organization_id == org_id)
        .where(Integration.type == IntegrationType.GITLAB)
        .where(Integration.status == "ACTIVE")
    )
    integration = result.scalar_one_or_none()
    
    if not integration or not integration.base_url or not integration.api_key:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Gitea integration not configured"
        )
    
    gitea = GiteaService(integration.base_url, integration.api_key)
    content = await gitea.get_file(owner, repo, path, ref)
    
    if content is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="File not found"
        )
    
    return {"path": path, "content": content, "ref": ref}
