"""AI-powered question tagging/classification — subjects, diseases, keywords.
Tables are created via raw SQL in setup_pgvector() to avoid race conditions with multiple workers.
"""
import logging
import uuid

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import text
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.user import User
from app.utils.auth import get_current_user, require_moderator

router = APIRouter()
log = logging.getLogger(__name__)


@router.get("")
def get_tags(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    """Return all tags grouped by type, with question counts."""
    rows = db.execute(text("""
        SELECT t.id, t.name, t.type, COUNT(tl.question_id) AS count
        FROM question_tags t
        LEFT JOIN question_tag_links tl ON tl.tag_id = t.id
        GROUP BY t.id, t.name, t.type
        ORDER BY count DESC, t.name
    """)).fetchall()

    result = {"subjects": [], "diseases": [], "keywords": []}
    for r in rows:
        key = {"subject": "subjects", "disease": "diseases", "keyword": "keywords"}.get(r.type)
        if key:
            result[key].append({"id": r.id, "name": r.name, "count": r.count})
    return result


@router.post("/classify")
def trigger_classification(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_moderator),
):
    """Admin/moderator: trigger background classification of untagged questions."""
    from app.tasks.quiz_tasks import classify_questions

    job_id = str(uuid.uuid4())
    classify_questions.delay(job_id, current_user.id)
    return {"job_id": job_id, "status": "started"}


@router.get("/status/{job_id}")
def get_classification_status(
    job_id: str,
    current_user: User = Depends(get_current_user),
):
    """Check classification job progress."""
    import json
    import redis
    from app.config import settings

    r = redis.from_url(settings.REDIS_URL, decode_responses=True)
    status = r.get(f"classify:status:{job_id}") or "unknown"
    steps_raw = r.lrange(f"classify:steps:{job_id}", 0, -1)
    steps = [json.loads(s) for s in steps_raw] if steps_raw else []
    error = r.get(f"classify:error:{job_id}")

    return {"job_id": job_id, "status": status, "steps": steps, "error": error}
