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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
"""
Router de Foros Comunitarios de Melodix.

Endpoints públicos (sin auth): listar hilos, ver detalle de hilo.
Endpoints protegidos (con auth): crear hilo, responder, eliminar propio.
"""
import logging
from typing import Optional
from datetime import datetime
import time
from collections import defaultdict

from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.orm import Session
from sqlalchemy import func, or_
from pydantic import BaseModel

from app.database import get_db
from app.models.forum import ForumThread, ForumReply
from app.models.user import User
from app.routers.auth import get_current_user, oauth2_scheme
from app.utils.notifications import create_admin_notification

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/forums", tags=["forums"])


# ==========================================
# SCHEMAS
# ==========================================

class ThreadCreate(BaseModel):
    title: str
    body: str

class ReplyCreate(BaseModel):
    body: str

class UserBrief(BaseModel):
    id: int
    username: str
    avatar_url: Optional[str] = None

    class Config:
        from_attributes = True

class ReplyOut(BaseModel):
    id: int
    thread_id: int
    body: str
    created_at: datetime
    user: UserBrief

    class Config:
        from_attributes = True

class ThreadSummary(BaseModel):
    id: int
    title: str
    body: str
    created_at: datetime
    updated_at: Optional[datetime] = None
    reply_count: int
    user: UserBrief
    replies: Optional[list[ReplyOut]] = []


class ThreadDetail(BaseModel):
    id: int
    title: str
    body: str
    created_at: datetime
    updated_at: Optional[datetime] = None
    user: UserBrief
    replies: list[ReplyOut]


# ==========================================
# HELPER: Optional auth (devuelve None si no hay token)
# ==========================================

def get_optional_user(
    db: Session = Depends(get_db),
    token: Optional[str] = Depends(oauth2_scheme)
):
    """Intenta extraer el usuario del token, pero no falla si no hay token."""
    if not token:
        return None
    try:
        return get_current_user(token=token, db=db)
    except Exception:
        return None


class RateLimiter:
    def __init__(self, requests: int, window_secs: int):
        self.requests = requests
        self.window_secs = window_secs
        self.history = defaultdict(list)

    def __call__(self, current_user: User = Depends(get_current_user)):
        key = current_user.id
        now = time.time()
        # Filtrar timestamps que estén fuera de la ventana de tiempo
        self.history[key] = [t for t in self.history[key] if now - t < self.window_secs]

        if len(self.history[key]) >= self.requests:
            raise HTTPException(
                status_code=status.HTTP_429_TOO_MANY_REQUESTS,
                detail="Has excedido el límite de publicaciones. Por favor, espera un momento."
            )
        self.history[key].append(now)


# Limitadores: máximo 2 hilos por minuto y 5 respuestas por minuto
thread_limiter = RateLimiter(requests=2, window_secs=60)
reply_limiter = RateLimiter(requests=5, window_secs=60)


# ==========================================
# PUBLIC ENDPOINTS (no auth required)
# ==========================================

@router.get("/threads", response_model=list[ThreadSummary])
def list_threads(
    q: Optional[str] = Query(None, description="Buscar por título o contenido"),
    skip: int = Query(0, ge=0),
    limit: int = Query(30, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """
    Lista todos los hilos del foro (paginados).
    Búsqueda opcional por ?q=texto que filtra por título y cuerpo.
    """
    query = db.query(ForumThread).filter(ForumThread.is_deleted == False)

    if q and q.strip():
        search_term = f"%{q.strip()}%"
        query = query.filter(
            or_(
                ForumThread.title.ilike(search_term),
                ForumThread.body.ilike(search_term)
            )
        )

    # Ordenar por más reciente primero
    threads = query.order_by(ForumThread.created_at.desc()).offset(skip).limit(limit).all()

    if not threads:
        return []

    thread_ids = [t.id for t in threads]

    # 1. Obtener conteos de respuestas de todos los hilos en una consulta agrupada (SQL group_by)
    counts_query = db.query(
        ForumReply.thread_id,
        func.count(ForumReply.id).label("count")
    ).filter(
        ForumReply.thread_id.in_(thread_ids),
        ForumReply.is_deleted == False
    ).group_by(ForumReply.thread_id).all()
    counts_map = {row[0]: row[1] for row in counts_query}

    # 2. Obtener las respuestas activas de todos los hilos en una sola consulta
    all_replies = db.query(ForumReply).filter(
        ForumReply.thread_id.in_(thread_ids),
        ForumReply.is_deleted == False
    ).order_by(ForumReply.created_at.asc()).all()

    # Agrupar las primeras 3 respuestas de cada hilo en memoria (Python)
    replies_map = defaultdict(list)
    for r in all_replies:
        if len(replies_map[r.thread_id]) < 3:
            replies_map[r.thread_id].append(r)

    result = []
    for t in threads:
        reply_count = counts_map.get(t.id, 0)
        thread_replies = replies_map[t.id]

        replies_out = [
            ReplyOut(
                id=r.id,
                thread_id=r.thread_id,
                body=r.body,
                created_at=r.created_at,
                user=UserBrief(
                    id=r.user.id,
                    username=r.user.username,
                    avatar_url=r.user.avatar_url
                )
            )
            for r in thread_replies
        ]
        
        result.append(ThreadSummary(
            id=t.id,
            title=t.title,
            body=t.body,
            created_at=t.created_at,
            updated_at=t.updated_at,
            reply_count=reply_count,
            user=UserBrief(
                id=t.user.id,
                username=t.user.username,
                avatar_url=t.user.avatar_url
            ),
            replies=replies_out
        ))

    return result


@router.get("/threads/{thread_id}", response_model=ThreadDetail)
def get_thread(thread_id: int, db: Session = Depends(get_db)):
    """
    Obtiene el detalle de un hilo con todas sus respuestas.
    """
    thread = db.query(ForumThread).filter(
        ForumThread.id == thread_id,
        ForumThread.is_deleted == False
    ).first()
    
    if not thread:
        raise HTTPException(status_code=404, detail="Hilo no encontrado")

    replies = db.query(ForumReply).filter(
        ForumReply.thread_id == thread_id,
        ForumReply.is_deleted == False
    ).order_by(ForumReply.created_at.asc()).all()

    return ThreadDetail(
        id=thread.id,
        title=thread.title,
        body=thread.body,
        created_at=thread.created_at,
        updated_at=thread.updated_at,
        user=UserBrief(
            id=thread.user.id,
            username=thread.user.username,
            avatar_url=thread.user.avatar_url
        ),
        replies=[
            ReplyOut(
                id=r.id,
                thread_id=r.thread_id,
                body=r.body,
                created_at=r.created_at,
                user=UserBrief(
                    id=r.user.id,
                    username=r.user.username,
                    avatar_url=r.user.avatar_url
                )
            )
            for r in replies
        ]
    )


# ==========================================
# PROTECTED ENDPOINTS (auth required)
# ==========================================

@router.post("/threads", response_model=ThreadDetail, status_code=201)
def create_thread(
    data: ThreadCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    _rate: None = Depends(thread_limiter)
):
    """Crea un nuevo hilo en el foro. Requiere autenticación."""
    if current_user.is_forum_banned:
        raise HTTPException(status_code=403, detail="Tu cuenta ha sido suspendida del foro por un administrador.")
        
    if not data.title.strip():
        raise HTTPException(status_code=400, detail="El título es obligatorio")
    if len(data.title.strip()) > 100:
        raise HTTPException(status_code=400, detail="El título no puede superar los 100 caracteres")
    if not data.body.strip():
        raise HTTPException(status_code=400, detail="El contenido es obligatorio")
    if len(data.body.strip()) > 3000:
        raise HTTPException(status_code=400, detail="El contenido no puede superar los 3000 caracteres")

    thread = ForumThread(
        user_id=current_user.id,
        title=data.title.strip(),
        body=data.body.strip()
    )
    db.add(thread)
    db.commit()
    db.refresh(thread)

    logger.info(f"[Foro] Nuevo hilo #{thread.id} por {current_user.username}: {thread.title}")

    # Registrar en el log de administración
    try:
        create_admin_notification(
            db,
            title="Nuevo hilo en el foro",
            message=f"El usuario '{current_user.username}' publicó un nuevo hilo: '{thread.title}'.",
            category="forum"
        )
    except Exception:
        pass  # No interrumpir la creación si falla la notificación

    return ThreadDetail(
        id=thread.id,
        title=thread.title,
        body=thread.body,
        created_at=thread.created_at,
        updated_at=thread.updated_at,
        user=UserBrief(
            id=current_user.id,
            username=current_user.username,
            avatar_url=current_user.avatar_url
        ),
        replies=[]
    )


@router.delete("/threads/{thread_id}", status_code=204)
def delete_thread(
    thread_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Elimina (soft-delete) un hilo. Solo el autor puede eliminarlo."""
    thread = db.query(ForumThread).filter(
        ForumThread.id == thread_id,
        ForumThread.is_deleted == False
    ).first()

    if not thread:
        raise HTTPException(status_code=404, detail="Hilo no encontrado")
    
    if thread.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Solo el autor puede eliminar este hilo")

    thread.is_deleted = True
    db.commit()
    logger.info(f"[Foro] Hilo #{thread_id} eliminado (soft) por {current_user.username}")


@router.post("/threads/{thread_id}/replies", response_model=ReplyOut, status_code=201)
def create_reply(
    thread_id: int,
    data: ReplyCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
    _rate: None = Depends(reply_limiter)
):
    """Responde a un hilo del foro. Requiere autenticación."""
    if current_user.is_forum_banned:
        raise HTTPException(status_code=403, detail="Tu cuenta ha sido suspendida del foro por un administrador.")

    thread = db.query(ForumThread).filter(
        ForumThread.id == thread_id,
        ForumThread.is_deleted == False
    ).first()

    if not thread:
        raise HTTPException(status_code=404, detail="Hilo no encontrado")

    if not data.body.strip():
        raise HTTPException(status_code=400, detail="La respuesta no puede estar vacía")
    if len(data.body.strip()) > 3000:
        raise HTTPException(status_code=400, detail="La respuesta no puede superar los 3000 caracteres")

    reply = ForumReply(
        thread_id=thread_id,
        user_id=current_user.id,
        body=data.body.strip()
    )
    db.add(reply)
    
    # Actualizar el updated_at del hilo para que suba en relevancia
    thread.updated_at = datetime.utcnow()
    
    db.commit()
    db.refresh(reply)

    logger.info(f"[Foro] Nueva respuesta #{reply.id} en hilo #{thread_id} por {current_user.username}")

    return ReplyOut(
        id=reply.id,
        thread_id=reply.thread_id,
        body=reply.body,
        created_at=reply.created_at,
        user=UserBrief(
            id=current_user.id,
            username=current_user.username,
            avatar_url=current_user.avatar_url
        )
    )


@router.delete("/replies/{reply_id}", status_code=204)
def delete_reply(
    reply_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Elimina (soft-delete) una respuesta. Solo el autor puede eliminarla."""
    reply = db.query(ForumReply).filter(
        ForumReply.id == reply_id,
        ForumReply.is_deleted == False
    ).first()

    if not reply:
        raise HTTPException(status_code=404, detail="Respuesta no encontrada")

    if reply.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Solo el autor puede eliminar esta respuesta")

    reply.is_deleted = True
    db.commit()
    logger.info(f"[Foro] Respuesta #{reply_id} eliminada (soft) por {current_user.username}")


@router.put("/threads/{thread_id}", response_model=ThreadDetail)
def update_thread(
    thread_id: int,
    data: ThreadCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Edita un hilo. Solo el autor puede editarlo dentro de los primeros 10 minutos."""
    thread = db.query(ForumThread).filter(
        ForumThread.id == thread_id,
        ForumThread.is_deleted == False
    ).first()

    if not thread:
        raise HTTPException(status_code=404, detail="Hilo no encontrado")
    
    if thread.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Solo el autor puede editar este hilo")

    # Validar límite de 10 minutos
    elapsed_minutes = (datetime.utcnow() - thread.created_at).total_seconds() / 60.0
    if elapsed_minutes > 10.0:
        raise HTTPException(
            status_code=400,
            detail="El tiempo límite de 10 minutos para editar este hilo ha expirado."
        )

    if not data.title.strip():
        raise HTTPException(status_code=400, detail="El título es obligatorio")
    if len(data.title.strip()) > 100:
        raise HTTPException(status_code=400, detail="El título no puede superar los 100 caracteres")
    if not data.body.strip():
        raise HTTPException(status_code=400, detail="El contenido es obligatorio")
    if len(data.body.strip()) > 3000:
        raise HTTPException(status_code=400, detail="El contenido no puede superar los 3000 caracteres")

    thread.title = data.title.strip()
    thread.body = data.body.strip()
    thread.updated_at = datetime.utcnow()
    db.commit()
    db.refresh(thread)

    logger.info(f"[Foro] Hilo #{thread_id} editado por {current_user.username}")

    replies = db.query(ForumReply).filter(
        ForumReply.thread_id == thread_id,
        ForumReply.is_deleted == False
    ).order_by(ForumReply.created_at.asc()).all()

    return ThreadDetail(
        id=thread.id,
        title=thread.title,
        body=thread.body,
        created_at=thread.created_at,
        updated_at=thread.updated_at,
        user=UserBrief(
            id=thread.user.id,
            username=thread.user.username,
            avatar_url=thread.user.avatar_url
        ),
        replies=[
            ReplyOut(
                id=r.id,
                thread_id=r.thread_id,
                body=r.body,
                created_at=r.created_at,
                user=UserBrief(
                    id=r.user.id,
                    username=r.user.username,
                    avatar_url=r.user.avatar_url
                )
            )
            for r in replies
        ]
    )


@router.put("/replies/{reply_id}", response_model=ReplyOut)
def update_reply(
    reply_id: int,
    data: ReplyCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Edita una respuesta. Solo el autor puede editarla dentro de los primeros 10 minutos."""
    reply = db.query(ForumReply).filter(
        ForumReply.id == reply_id,
        ForumReply.is_deleted == False
    ).first()

    if not reply:
        raise HTTPException(status_code=404, detail="Respuesta no encontrada")

    if reply.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="Solo el autor puede editar esta respuesta")

    # Validar límite de 10 minutos
    elapsed_minutes = (datetime.utcnow() - reply.created_at).total_seconds() / 60.0
    if elapsed_minutes > 10.0:
        raise HTTPException(
            status_code=400,
            detail="El tiempo límite de 10 minutos para editar esta respuesta ha expirado."
        )

    if not data.body.strip():
        raise HTTPException(status_code=400, detail="La respuesta no puede estar vacía")
    if len(data.body.strip()) > 3000:
        raise HTTPException(status_code=400, detail="La respuesta no puede superar los 3000 caracteres")

    reply.body = data.body.strip()
    db.commit()
    db.refresh(reply)

    logger.info(f"[Foro] Respuesta #{reply_id} editada por {current_user.username}")

    return ReplyOut(
        id=reply.id,
        thread_id=reply.thread_id,
        body=reply.body,
        created_at=reply.created_at,
        user=UserBrief(
            id=reply.user.id,
            username=reply.user.username,
            avatar_url=reply.user.avatar_url
        )
    )