# history_manager.py
#
# Copyright 2025 Pavel Baksy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
# SPDX-License-Identifier: GPL-3.0-or-later

import json
import os
import logging
from pathlib import Path
from typing import List
import gi
gi.require_version('GLib', '2.0')
from gi.repository import GLib
from .models import HistoryEntry
from .constants import HISTORY_MAX_ENTRIES

logger = logging.getLogger(__name__)


class HistoryManager:
    """Manages request history persistence to JSON file."""

    def __init__(self):
        # Use XDG config directory (works for both Flatpak and native)
        # Flatpak: ~/.var/app/cz.bugsy.roster/config/cz.bugsy.roster
        # Native: ~/.config/cz.bugsy.roster
        self.config_dir = Path(GLib.get_user_config_dir()) / 'cz.bugsy.roster'
        self.history_file = self.config_dir / 'history.json'
        self._ensure_config_dir()

    def _ensure_config_dir(self):
        """Create config directory if it doesn't exist."""
        self.config_dir.mkdir(parents=True, exist_ok=True)

    def load_history(self) -> List[HistoryEntry]:
        """Load history from JSON file."""
        if not self.history_file.exists():
            return []

        try:
            with open(self.history_file, 'r') as f:
                data = json.load(f)

            return [HistoryEntry.from_dict(entry) for entry in data.get('entries', [])]
        except Exception as e:
            logger.error(f"Error loading history: {e}")
            return []

    def save_history(self, entries: List[HistoryEntry]):
        """Save history to JSON file."""
        try:
            data = {
                'version': 1,
                'entries': [entry.to_dict() for entry in entries]
            }

            with open(self.history_file, 'w') as f:
                json.dump(data, f, indent=2)
        except Exception as e:
            logger.error(f"Error saving history: {e}")

    def add_entry(self, entry: HistoryEntry):
        """Add new entry to history and save."""
        entries = self.load_history()
        entries.insert(0, entry)  # Most recent first

        # Limit history size
        entries = entries[:HISTORY_MAX_ENTRIES]

        self.save_history(entries)

    def delete_entry(self, entry: HistoryEntry):
        """Delete a specific entry from history by ID."""
        entries = self.load_history()
        # Filter out the entry by comparing unique IDs
        entries = [e for e in entries if e.id != entry.id]
        self.save_history(entries)

    def clear_history(self):
        """Clear all history entries."""
        self.save_history([])
