"""
Feedback Tracker
Stores feedback records to a JSON file for tracking and resolution.
Lightweight alternative to MongoDB — can migrate later.
"""

import json
import logging
import os
from datetime import datetime, timezone
from typing import Optional

logger = logging.getLogger(__name__)

# Store feedbacks in a JSON file alongside the backend
FEEDBACK_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "feedbacks.json")


def _ensure_data_dir():
    """Ensure the data directory exists."""
    data_dir = os.path.dirname(FEEDBACK_FILE)
    if not os.path.exists(data_dir):
        os.makedirs(data_dir, exist_ok=True)


def _load_feedbacks() -> list[dict]:
    """Load all feedbacks from file."""
    _ensure_data_dir()
    if not os.path.exists(FEEDBACK_FILE):
        return []
    try:
        with open(FEEDBACK_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except (json.JSONDecodeError, IOError):
        return []


def _save_feedbacks(feedbacks: list[dict]):
    """Save feedbacks to file."""
    _ensure_data_dir()
    with open(FEEDBACK_FILE, "w", encoding="utf-8") as f:
        json.dump(feedbacks, f, ensure_ascii=False, indent=2, default=str)


def save_feedback(
    trace_id: str,
    rating: int,
    comment: str = "",
    user_category: str = "",
    ai_category: str = "",
    ai_severity: str = "",
    ai_summary: str = "",
) -> dict:
    """
    Save a feedback record.

    Returns:
        The saved feedback dict.
    """
    feedback = {
        "trace_id": trace_id,
        "rating": rating,
        "comment": comment,
        "user_category": user_category,
        "ai_category": ai_category,
        "ai_severity": ai_severity,
        "ai_summary": ai_summary,
        "processed": False,
        "created_at": datetime.now(timezone.utc).isoformat(),
    }

    feedbacks = _load_feedbacks()
    feedbacks.append(feedback)
    _save_feedbacks(feedbacks)

    logger.info(f"💾 Feedback saved: trace={trace_id}, rating={rating}, category={ai_category}")
    return feedback


def get_unprocessed() -> list[dict]:
    """Get all unprocessed feedbacks."""
    feedbacks = _load_feedbacks()
    return [f for f in feedbacks if not f.get("processed", False)]


def mark_processed(trace_id: str) -> bool:
    """Mark a feedback as processed."""
    feedbacks = _load_feedbacks()
    found = False
    for f in feedbacks:
        if f["trace_id"] == trace_id and not f.get("processed", False):
            f["processed"] = True
            f["processed_at"] = datetime.now(timezone.utc).isoformat()
            found = True

    if found:
        _save_feedbacks(feedbacks)
        logger.info(f"✅ Feedback marked processed: {trace_id}")

    return found


def get_all_feedbacks(limit: int = 100, offset: int = 0) -> list[dict]:
    """Get all feedbacks with pagination."""
    feedbacks = _load_feedbacks()
    feedbacks.sort(key=lambda x: x.get("created_at", ""), reverse=True)
    return feedbacks[offset : offset + limit]


def get_feedback_stats() -> dict:
    """Get feedback statistics."""
    feedbacks = _load_feedbacks()
    total = len(feedbacks)
    likes = sum(1 for f in feedbacks if f.get("rating") == 1)
    dislikes = sum(1 for f in feedbacks if f.get("rating") == 0)
    unprocessed = sum(1 for f in feedbacks if not f.get("processed", False))

    categories = {}
    for f in feedbacks:
        cat = f.get("ai_category", "unknown")
        categories[cat] = categories.get(cat, 0) + 1

    return {
        "total": total,
        "likes": likes,
        "dislikes": dislikes,
        "unprocessed": unprocessed,
        "categories": categories,
    }
