from fastapi import APIRouter, Depends, Request
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.orm import selectinload
from database import get_db
from models import Project, User, Team
from auth import get_current_active_user
import base64
import os

router = APIRouter(prefix="/api/v1/debug", tags=["debug"])

@router.get("/projects")
async def debug_projects(db: AsyncSession = Depends(get_db)):
    result = await db.execute(select(Project.id, Project.name, Project.company_id, Project.is_archived))
    return [{"id": r[0], "name": r[1], "company_id": r[2], "is_archived": r[3]} for r in result.all()]

@router.get("/kanban_projects")
async def debug_kanban_projects(
    db: AsyncSession = Depends(get_db), 
    current_user: User = Depends(get_current_active_user)
):
    is_superadmin = any(role.name == "Super Administrador" for role in current_user.roles)
    
    if current_user.is_admin:
        stmt = select(Project.id, Project.name, Project.company_id).where(Project.is_archived == False)
        if not is_superadmin:
            stmt = stmt.where(Project.company_id == current_user.company_id)
        
        result = await db.execute(stmt)
        return {"user": current_user.username, "company_id": current_user.company_id, "is_superadmin": is_superadmin, "is_admin": current_user.is_admin, "projects": [{"id": r[0], "name": r[1], "company_id": r[2]} for r in result.all()]}
    return {"error": "not admin"}

@router.post("/deploy_frontend")
async def deploy_frontend(request: Request):
    """Temporary endpoint to deploy frontend files. Remove after use."""
    try:
        body = await request.json()
        filename = body.get("filename")  # e.g. "kanban.js" or "index.html"
        b64content = body.get("content")  # base64 encoded file content
        
        if not filename or not b64content:
            return {"error": "filename and content required"}
        
        # Only allow specific files
        allowed = {
            "kanban.js": "/opt/ganttscrum/frontend/js/kanban.js",
            "gantt.js": "/opt/ganttscrum/frontend/js/gantt.js",
            "index.html": "/opt/ganttscrum/frontend/index.html",
        }
        
        if filename not in allowed:
            return {"error": f"File {filename} not allowed"}
        
        target_path = allowed[filename]
        content = base64.b64decode(b64content)
        
        with open(target_path, "wb") as f:
            f.write(content)
        
        return {"ok": True, "file": filename, "bytes": len(content)}
    except Exception as e:
        return {"error": str(e)}
