from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from typing import List

from database import get_db
from models.user import User, UserRole
from models.project import Project, ProjectMember
from models.task import Task, Submission
from models.api_key import APIKey
from models.api_key_usage import APIKeyUsage
from schemas.project import ProjectResponse
from schemas.task import TaskResponse, SubmissionResponse
from schemas.api_key import APIKeyUsageLog
from utils.auth import get_current_user_flexible, require_api_key_scope

router = APIRouter()


@router.get("/projects", response_model=List[ProjectResponse])
async def get_all_projects_for_developer(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_api_key_scope("read:projects"))
):
    """Get read-only access to all projects for developers."""
    # Ensure user is a developer
    if current_user.role != UserRole.DEVELOPER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only developers can access this endpoint"
        )
    
    # Get all projects
    projects = db.query(Project).all()
    
    result = []
    for project in projects:
        # Get member count
        member_count = db.query(ProjectMember).filter(ProjectMember.project_id == project.id).count()
        
        result.append(ProjectResponse(
            id=project.id,
            name=project.name,
            description=project.description,
            status=project.status,
            start_date=project.start_date,
            end_date=project.end_date,
            created_at=project.created_at,
            updated_at=project.updated_at,
            member_count=member_count
        ))
    
    return result


@router.get("/tasks", response_model=List[TaskResponse])
async def get_all_tasks_for_developer(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_api_key_scope("read:tasks")),
    project_id: int = None,
    limit: int = 100,
    offset: int = 0
):
    """Get read-only access to all tasks across projects for developers."""
    # Ensure user is a developer
    if current_user.role != UserRole.DEVELOPER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only developers can access this endpoint"
        )
    
    # Build query
    query = db.query(Task)
    
    # Filter by project if specified
    if project_id:
        query = query.filter(Task.project_id == project_id)
    
    # Apply pagination
    tasks = query.offset(offset).limit(limit).all()
    
    result = []
    for task in tasks:
        # Get assigned user info
        assigned_user = None
        if task.assigned_user_id:
            user = db.query(User).filter(User.id == task.assigned_user_id).first()
            if user:
                assigned_user = {
                    "id": user.id,
                    "first_name": user.first_name,
                    "last_name": user.last_name,
                    "email": user.email
                }
        
        # Get project info
        project = db.query(Project).filter(Project.id == task.project_id).first()
        project_info = None
        if project:
            project_info = {
                "id": project.id,
                "name": project.name
            }
        
        result.append(TaskResponse(
            id=task.id,
            project_id=task.project_id,
            episode_id=task.episode_id,
            shot_id=task.shot_id,
            asset_id=task.asset_id,
            assigned_user_id=task.assigned_user_id,
            task_type=task.task_type,
            name=task.name,
            description=task.description,
            status=task.status,
            deadline=task.deadline,
            created_at=task.created_at,
            updated_at=task.updated_at,
            assigned_user=assigned_user,
            project=project_info
        ))
    
    return result


@router.get("/submissions", response_model=List[SubmissionResponse])
async def get_all_submissions_for_developer(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_api_key_scope("read:submissions")),
    project_id: int = None,
    task_id: int = None,
    limit: int = 100,
    offset: int = 0
):
    """Get read-only access to all submissions for developers."""
    # Ensure user is a developer
    if current_user.role != UserRole.DEVELOPER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only developers can access this endpoint"
        )
    
    # Build query
    query = db.query(Submission).filter(Submission.deleted_at.is_(None))
    
    # Filter by task if specified
    if task_id:
        query = query.filter(Submission.task_id == task_id)
    elif project_id:
        # Filter by project through task relationship
        query = query.join(Task).filter(
            Task.project_id == project_id,
            Task.deleted_at.is_(None)
        )
    
    # Apply pagination
    submissions = query.offset(offset).limit(limit).all()
    
    result = []
    for submission in submissions:
        # Get task info
        task = db.query(Task).filter(Task.id == submission.task_id).first()
        task_info = None
        if task:
            task_info = {
                "id": task.id,
                "name": task.name,
                "task_type": task.task_type,
                "project_id": task.project_id
            }
        
        # Get user info
        user = db.query(User).filter(User.id == submission.user_id).first()
        user_info = None
        if user:
            user_info = {
                "id": user.id,
                "first_name": user.first_name,
                "last_name": user.last_name,
                "email": user.email
            }
        
        result.append(SubmissionResponse(
            id=submission.id,
            task_id=submission.task_id,
            user_id=submission.user_id,
            file_path=submission.file_path,
            file_name=submission.file_name,
            version_number=submission.version_number,
            notes=submission.notes,
            submitted_at=submission.submitted_at,
            task=task_info,
            user=user_info
        ))
    
    return result


@router.get("/api-usage", response_model=List[APIKeyUsageLog])
async def get_api_usage_logs(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user_flexible),
    limit: int = 100,
    offset: int = 0
):
    """Get API key usage logs for the current developer."""
    # Ensure user is a developer
    if current_user.role != UserRole.DEVELOPER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only developers can access this endpoint"
        )
    
    # Get usage logs for all API keys belonging to the current user
    usage_logs = db.query(APIKeyUsage).join(
        APIKey, APIKeyUsage.api_key_id == APIKey.id
    ).filter(
        APIKey.user_id == current_user.id
    ).order_by(
        APIKeyUsage.timestamp.desc()
    ).offset(offset).limit(limit).all()
    
    return [
        APIKeyUsageLog(
            api_key_id=log.api_key_id,
            endpoint=log.endpoint,
            method=log.method,
            timestamp=log.timestamp,
            ip_address=log.ip_address,
            user_agent=log.user_agent
        )
        for log in usage_logs
    ]


@router.get("/stats")
async def get_developer_stats(
    request: Request,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user_flexible)
):
    """Get statistics for developer dashboard."""
    # Ensure user is a developer
    if current_user.role != UserRole.DEVELOPER:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Only developers can access this endpoint"
        )
    
    # Get various counts
    total_projects = db.query(Project).count()
    total_tasks = db.query(Task).count()
    total_submissions = db.query(Submission).count()
    
    # Get API key usage count for current user
    api_usage_count = db.query(APIKeyUsage).join(
        APIKey, APIKeyUsage.api_key_id == APIKey.id
    ).filter(
        APIKey.user_id == current_user.id
    ).count()
    
    return {
        "total_projects": total_projects,
        "total_tasks": total_tasks,
        "total_submissions": total_submissions,
        "api_usage_count": api_usage_count
    }