import json
import uuid
from datetime import datetime
from pathlib import Path
from config import STORAGE_FILES, POSITION_FILE


def load_entries(category: str) -> list:
    """Load all entries from a category's JSON file."""
    file_path = STORAGE_FILES.get(category)
    if not file_path or not file_path.exists():
        return []
    with open(file_path, "r") as f:
        return json.load(f)


def save_entries(category: str, entries: list) -> None:
    """Save entries to a category's JSON file."""
    file_path = STORAGE_FILES.get(category)
    if not file_path:
        raise ValueError(f"Unknown category: {category}")
    with open(file_path, "w") as f:
        json.dump(entries, f, indent=2, ensure_ascii=False)


def add_entry(category: str, message: str, timestamp: str, confidence: float) -> dict:
    """Add a new entry to a category."""
    entry = {
        "id": str(uuid.uuid4()),
        "timestamp": timestamp,
        "raw_message": message,
        "category": category,
        "confidence": confidence,
        "processed_at": datetime.now().isoformat(),
    }
    entries = load_entries(category)
    entries.append(entry)
    save_entries(category, entries)
    return entry


def get_last_position() -> int:
    """Get the last processed line number from the log file."""
    if not POSITION_FILE.exists():
        return 0
    with open(POSITION_FILE, "r") as f:
        content = f.read().strip()
        return int(content) if content else 0


def save_position(line_number: int) -> None:
    """Save the last processed line number."""
    with open(POSITION_FILE, "w") as f:
        f.write(str(line_number))
