import sys
sys.path.insert(0, "/var/www/html/metafoliadorv2")
from fastapi import APIRouter, Depends, HTTPException, Path
from sqlalchemy.orm import Session
from app.models.database import get_db
from app.models.reporte import Reporte
from app.models.user import User
from app.schemas import CreateReporteRequest, UpdateReporteRequest
from app.api.routes.auth import get_current_user, require_permission
from app.services.timezone import iso

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

@router.get("", summary="Listar reportes", description="Lista todos los reportes disponibles con su estado activo/inactivo, tipo y URL.")
async def list_reportes(db: Session = Depends(get_db)):
    reportes = db.query(Reporte).order_by(Reporte.name).all()
    return [{
        "id": r.id, "name": r.name, "code": r.code, "description": r.description,
        "active": r.active, "type_report": r.type_report, "url_report": r.url_report,
        "created_at": iso(r.created_at),
    } for r in reportes]

@router.get("/{reporte_id}", summary="Obtener reporte", description="Devuelve el detalle de un reporte por su ID.")
async def get_reporte(reporte_id: int = Path(..., description="ID del reporte"), db: Session = Depends(get_db)):
    r = db.query(Reporte).filter(Reporte.id == reporte_id).first()
    if not r: raise HTTPException(status_code=404, detail="Reporte no encontrado")
    return {
        "id": r.id, "name": r.name, "code": r.code, "description": r.description,
        "active": r.active, "type_report": r.type_report, "url_report": r.url_report,
        "created_at": iso(r.created_at),
    }

@router.post("", status_code=201, summary="Crear reporte", description="Crea un nuevo reporte externo (type_report=2) con URL. Requiere permiso reportes.create.")
async def create_reporte(body: CreateReporteRequest, db: Session = Depends(get_db), current_user: User = Depends(require_permission("reportes.create"))):
    if not body.name or not body.code:
        raise HTTPException(status_code=400, detail="Nombre y código son requeridos")
    existing = db.query(Reporte).filter(Reporte.code == body.code).first()
    if existing:
        raise HTTPException(status_code=409, detail="El código ya existe")
    if body.type_report == 2 and not body.url_report:
        raise HTTPException(status_code=400, detail="URL requerida para reportes externos")
    r = Reporte(
        name=body.name, code=body.code, description=body.description or "",
        type_report=body.type_report, url_report=body.url_report,
        active=body.active if body.active is not None else True,
    )
    db.add(r)
    db.commit()
    db.refresh(r)
    return {"ok": True, "id": r.id}

@router.put("/{reporte_id}", summary="Actualizar reporte", description="Modifica un reporte existente. Solo aplica a reportes externos (type_report=2). Requiere permiso reportes.edit.")
async def update_reporte(reporte_id: int = Path(..., description="ID del reporte"), body: UpdateReporteRequest = None, db: Session = Depends(get_db), current_user: User = Depends(require_permission("reportes.edit"))):
    r = db.query(Reporte).filter(Reporte.id == reporte_id).first()
    if not r: raise HTTPException(status_code=404, detail="Reporte no encontrado")
    if r.type_report == 1:
        raise HTTPException(status_code=400, detail="No se puede editar un reporte interno")
    if body.name is not None: r.name = body.name
    if body.code is not None:
        existing = db.query(Reporte).filter(Reporte.code == body.code, Reporte.id != reporte_id).first()
        if existing: raise HTTPException(status_code=409, detail="El código ya existe")
        r.code = body.code
    if body.description is not None: r.description = body.description
    if body.type_report is not None: r.type_report = body.type_report
    if body.url_report is not None: r.url_report = body.url_report
    if body.active is not None: r.active = body.active
    db.commit()
    return {"ok": True}

@router.delete("/{reporte_id}", summary="Eliminar reporte", description="Elimina permanentemente un reporte externo. No se pueden eliminar reportes internos. Requiere permiso reportes.delete.")
async def delete_reporte(reporte_id: int = Path(..., description="ID del reporte a eliminar"), db: Session = Depends(get_db), current_user: User = Depends(require_permission("reportes.delete"))):
    r = db.query(Reporte).filter(Reporte.id == reporte_id).first()
    if not r: raise HTTPException(status_code=404, detail="Reporte no encontrado")
    if r.type_report == 1:
        raise HTTPException(status_code=400, detail="No se puede eliminar un reporte interno")
    db.delete(r)
    db.commit()
    return {"ok": True}

@router.put("/{reporte_id}/toggle", summary="Activar/inactivar reporte", description="Alterna el estado activo/inactivo de un reporte. Requiere permiso reportes.toggle.")
async def toggle_reporte(reporte_id: int = Path(..., description="ID del reporte"), db: Session = Depends(get_db), current_user: User = Depends(require_permission("reportes.toggle"))):
    r = db.query(Reporte).filter(Reporte.id == reporte_id).first()
    if not r: raise HTTPException(status_code=404, detail="Reporte no encontrado")
    r.active = not r.active
    db.commit()
    return {"ok": True, "active": r.active}
