"""Core business logic for Lettera."""

import aiofiles
from datetime import datetime
from pathlib import Path
from typing import Optional, List

from .config import Config
from .types import EntryMeta


class Service:
    """Core journaling operations."""

    def __init__(self, config: Optional[Config] = None):
        """Initialize service with config."""
        self.config = config or Config.load()
        self.entries_dir = Path(self.config.entries_dir).expanduser()
        self.entries_dir.mkdir(parents=True, exist_ok=True)

    def create_entry_path(self) -> Path:
        """Generate timestamped entry path (YYYY-MM-DDTHH-mm-ss.md)."""
        timestamp = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
        filename = f"{timestamp}.md"
        return self.entries_dir / filename

    async def save_entry(self, path: Path, content: str) -> None:
        """Save entry content to file."""
        async with aiofiles.open(path, 'w', encoding='utf-8') as f:
            await f.write(content)

    async def load_entry(self, path: Path) -> str:
        """Load entry content from file."""
        async with aiofiles.open(path, 'r', encoding='utf-8') as f:
            return await f.read()

    async def list_entries(self) -> List[EntryMeta]:
        """List all entries, most recent first."""
        entries = []
        for path in self.entries_dir.glob("*.md"):
            try:
                # Parse timestamp from filename (format: YYYY-MM-DDTHH-mm-ss)
                filename = path.stem
                created = datetime.strptime(filename, "%Y-%m-%dT%H-%M-%S")

                entries.append(
                    EntryMeta(path=path, filename=filename, created=created)
                )
            except (ValueError, IndexError):
                # Skip files that don't match expected format
                continue

        return sorted(entries, key=lambda e: e.created, reverse=True)
