"""
task_formatter.py — Serialisasi task dengan dekripsi + court mode + partial result.

Perubahan:
- task_to_response() sekarang menyertakan partial_result dan segments
  agar frontend bisa menampilkan hasil sementara saat status=processing.
- Jika status=completed, result didekripsi dari DB (Fernet).
- Jika status=processing, partial_result dikembalikan as-is (plaintext).
- segments_json di-parse menjadi list of dict untuk konsumsi frontend.
"""

import json
from typing import Optional

from app.models.transkripsi import TranskripsiTask
from app.utils.court import apply_court_mode
from app.utils.crypto_utils import decrypt_text


def format_task_result(task: TranskripsiTask) -> Optional[str]:
    """
    Dekripsi result final dan terapkan court mode jika relevan.
    Hanya untuk task dengan status 'completed'.
    """
    raw = task.result
    if not raw:
        return raw

    text = decrypt_text(raw)

    # Court mode sudah diterapkan saat simpan di transcription_service,
    # tapi kita terapkan lagi di sini sebagai fallback untuk data lama
    # yang belum diproses court mode saat disimpan.
    if task.status == "completed" and task.is_court_mode:
        text = apply_court_mode(text, is_court_mode=True)

    return text


def _parse_segments(segments_json: Optional[str]) -> list:
    """Parse segments_json string menjadi list. Return [] jika kosong/invalid."""
    if not segments_json:
        return []
    try:
        parsed = json.loads(segments_json)
        return parsed if isinstance(parsed, list) else []
    except (json.JSONDecodeError, TypeError):
        return []


def task_to_response(task: TranskripsiTask) -> dict:
    """
    Serialisasi task ke dict response yang aman untuk client.

    - Status completed  → result berisi teks final (didekripsi).
    - Status processing → result=None, partial_result berisi teks sementara,
                          segments berisi list [{start, end, text}].
    - Status lain       → result=None, partial_result=None.
    """
    is_completed = task.status == "completed"
    is_processing = task.status == "processing"

    return {
        "id":              task.id,
        "task_id":         task.id,
        "task_uuid":       task.task_uuid,
        "status":          task.status,
        "progress":        task.progress,
        # Hasil final (hanya saat completed)
        "result":          format_task_result(task) if is_completed else None,
        # Hasil sementara (hanya saat processing)
        "partial_result":  task.partial_result if is_processing else None,
        # Segmen dengan timestamp (hanya saat processing)
        "segments":        _parse_segments(task.segments_json) if is_processing else [],
        "error_message":   task.error_message,
        "engine":          task.engine,
        "model_type":      task.model_type,
        "is_court_mode":   task.is_court_mode,
        "is_cancelled":    task.is_cancelled,
        "processing_time": task.processing_time,
        "audio_duration":  task.audio_duration,
        "user_id":         getattr(task, "user_id", None),
        "created_at":      task.created_at.isoformat() if task.created_at else None,
    }


def task_to_admin_response(task: TranskripsiTask) -> dict:
    """Response untuk admin — sama dengan task_to_response() + field tambahan."""
    base = task_to_response(task)
    base.update({
        "audio_file": task.audio_file,
        "updated_at": task.updated_at.isoformat() if task.updated_at else None,
    })
    return base