import { NextRequest, NextResponse } from "next/server"; import { db } from "@/lib/db"; import ZAI from "z-ai-web-dev-sdk"; // Reglas de censura por plataforma y categoría const DEFAULT_CENSOR_RULES = [ // YouTube { platform: "youtube", category: "nudity", rule: "No se permite desnudez ni contenido sexual", severity: "high", autoAction: "remove" }, { platform: "youtube", category: "violence", rule: "Violencia gráfica no permitida sin advertencia", severity: "medium", autoAction: "warn" }, { platform: "youtube", category: "hate_speech", rule: "No se permite discurso de odio", severity: "high", autoAction: "remove" }, // TikTok { platform: "tiktok", category: "nudity", rule: "Cero tolerancia para desnudez", severity: "high", autoAction: "remove" }, { platform: "tiktok", category: "violence", rule: "Sin violencia gráfica", severity: "high", autoAction: "remove" }, { platform: "tiktok", category: "self_harm", rule: "No contenido de autolesión", severity: "high", autoAction: "remove" }, { platform: "tiktok", category: "dangerous", rule: "No desafíos peligrosos", severity: "high", autoAction: "remove" }, // Instagram { platform: "instagram", category: "nudity", rule: "No desnudez, excepto arte con moderación", severity: "high", autoAction: "blur" }, { platform: "instagram", category: "violence", rule: "Sin violencia gráfica", severity: "high", autoAction: "remove" }, // Twitter/X { platform: "twitter", category: "illegal", rule: "No contenido ilegal", severity: "high", autoAction: "remove" }, { platform: "twitter", category: "sensitive", rule: "Marcar como contenido sensible", severity: "low", autoAction: "warn" }, ]; // GET - Obtener reglas de censura export async function GET(request: NextRequest) { try { const { searchParams } = new URL(request.url); const platform = searchParams.get("platform"); let rules; if (platform) { rules = await db.censorRule.findMany({ where: { platform, isActive: true } }); // Si no hay reglas en BD, usar las por defecto if (rules.length === 0) { rules = DEFAULT_CENSOR_RULES.filter(r => r.platform === platform); } } else { rules = await db.censorRule.findMany({ where: { isActive: true } }); if (rules.length === 0) { rules = DEFAULT_CENSOR_RULES; } } return NextResponse.json({ success: true, rules }); } catch (error) { console.error("Error fetching censor rules:", error); return NextResponse.json( { success: false, error: "Error al obtener reglas de censura" }, { status: 500 } ); } } // POST - Analizar contenido para censura export async function POST(request: NextRequest) { try { const body = await request.json(); const { content, type, platform } = body; if (!content) { return NextResponse.json( { success: false, error: "Contenido requerido para análisis" }, { status: 400 } ); } const zai = await ZAI.create(); // Usar IA para analizar el contenido const analysisPrompt = `Analiza el siguiente ${type || "contenido"} para verificar si cumple con las normas de la plataforma ${platform || "general"}. Contenido a analizar: ${content.substring(0, 2000)} Responde SOLO en formato JSON: { "safe": true/false, "flags": [ {"category": "categoría", "reason": "razón", "severity": "low/medium/high"} ], "recommendations": ["recomendación1", "recomendación2"], "platformCompatible": ["plataforma1", "plataforma2"] }`; const completion = await zai.chat.completions.create({ messages: [ { role: "system", content: `Eres un moderador de contenido experto. Tu trabajo es analizar contenido para verificar si cumple con las políticas de diferentes plataformas. Sé estricto pero justo. Considera: 1. YouTube: Familiar, sin desnudez, violencia moderada con advertencia 2. TikTok: Para todos los públicos, sin contenido peligroso 3. Instagram: Sin desnudez (excepto arte), sin violencia gráfica 4. Twitter: Más permisivo pero marca contenido sensible 5. General: Apropiado para todo público` }, { role: "user", content: analysisPrompt } ], temperature: 0.3, }); const response = completion.choices[0]?.message?.content || ""; // Parsear respuesta let analysis; try { const jsonMatch = response.match(/\{[\s\S]*\}/); if (jsonMatch) { analysis = JSON.parse(jsonMatch[0]); } else { analysis = { safe: true, flags: [], recommendations: [], platformCompatible: [platform || "general"] }; } } catch { analysis = { safe: true, flags: [], recommendations: [], platformCompatible: [platform || "general"] }; } return NextResponse.json({ success: true, analysis, originalContent: content.substring(0, 200) }); } catch (error) { console.error("Error analyzing content:", error); return NextResponse.json( { success: false, error: "Error al analizar contenido" }, { status: 500 } ); } } // PUT - Añadir regla de censura personalizada export async function PUT(request: NextRequest) { try { const body = await request.json(); const { platform, category, rule, severity, autoAction } = body; if (!platform || !category || !rule) { return NextResponse.json( { success: false, error: "Plataforma, categoría y regla son requeridos" }, { status: 400 } ); } const censorRule = await db.censorRule.create({ data: { platform, category, rule, severity: severity || "medium", autoAction: autoAction || "warn" } }); return NextResponse.json({ success: true, rule: censorRule, message: "Regla de censura creada" }); } catch (error) { console.error("Error creating censor rule:", error); return NextResponse.json( { success: false, error: "Error al crear regla de censura" }, { status: 500 } ); } }