"""History management service."""

import json
import os
from datetime import datetime
from pathlib import Path
from typing import List, Optional
from ..config import get_config_dir


def get_history_file() -> Path:
    """Get the history file path."""
    return get_config_dir() / "history.json"


def load_history() -> List[dict]:
    """Load history from file."""
    history_file = get_history_file()
    if not history_file.exists():
        return []

    try:
        with open(history_file, 'r', encoding='utf-8') as f:
            return json.load(f)
    except (json.JSONDecodeError, Exception):
        return []


def save_history(history: List[dict]) -> None:
    """Save history to file."""
    history_file = get_history_file()
    with open(history_file, 'w', encoding='utf-8') as f:
        json.dump(history, f, indent=2, ensure_ascii=False)


def add_to_history(
    id: str,
    title: str,
    url: str,
    file_path: str,
    duration: Optional[str] = None,
    thumbnail: Optional[str] = None
) -> dict:
    """Add a new item to history."""
    history = load_history()

    item = {
        'id': id,
        'title': title,
        'url': url,
        'file_path': file_path,
        'created_at': datetime.now().isoformat(),
        'duration': duration,
        'thumbnail': thumbnail,
    }

    # Add to beginning of list
    history.insert(0, item)

    # Keep only last 100 items
    history = history[:100]

    save_history(history)
    return item


def get_history(search: Optional[str] = None, limit: int = 50, offset: int = 0) -> tuple:
    """
    Get history items with optional search.
    Searches in title and transcription text content.

    Returns (items, total_count)
    """
    history = load_history()

    if search:
        search_lower = search.lower()
        filtered = []
        for item in history:
            # Search in title
            if search_lower in item.get('title', '').lower():
                filtered.append(item)
                continue
            # Search in transcription text
            file_path = item.get('file_path')
            if file_path:
                text = get_transcription_text(file_path)
                if text and search_lower in text.lower():
                    filtered.append(item)
        history = filtered

    total = len(history)
    items = history[offset:offset + limit]

    return items, total


def get_history_item(id: str) -> Optional[dict]:
    """Get a specific history item by ID."""
    history = load_history()
    for item in history:
        if item.get('id') == id:
            return item
    return None


def delete_history_item(id: str) -> bool:
    """Delete a history item by ID."""
    history = load_history()
    original_len = len(history)

    history = [item for item in history if item.get('id') != id]

    if len(history) < original_len:
        save_history(history)
        return True
    return False


def clear_history() -> None:
    """Clear all history."""
    save_history([])


def get_transcription_text(file_path: str) -> Optional[str]:
    """Read transcription text from file."""
    try:
        if os.path.exists(file_path):
            with open(file_path, 'r', encoding='utf-8') as f:
                content = f.read()
                # Skip header if present
                if content.startswith('Title:'):
                    lines = content.split('\n')
                    # Find the separator line and skip past it
                    for i, line in enumerate(lines):
                        if line.startswith('==='):
                            return '\n'.join(lines[i+2:]).strip()
                return content
    except Exception:
        pass
    return None
