"""Append-only operation history for k4s.

``~/.k4s/history.jsonl`` records every meaningful action (install, configure,
cluster-create, tls-enable, …).  It is purely informational — no command
depends on reading it.  ``k4s history`` renders it for the user.
"""
import json
import logging
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional

logger = logging.getLogger(__name__)


class HistoryManager:
    """Manage the append-only operations log under ``~/.k4s/history.jsonl``."""

    def __init__(self, base_dir: Optional[Path] = None):
        self.base_dir = base_dir or (Path.home() / ".k4s")
        self.history_path = self.base_dir / "history.jsonl"
        self.base_dir.mkdir(parents=True, exist_ok=True)

    def append(
        self,
        action: str,
        product: str,
        *,
        context: Optional[str] = None,
        host: Optional[str] = None,
        params: Optional[Dict[str, Any]] = None,
        result: str = "success",
    ) -> None:
        """Append an entry to the operations history log.

        Args:
            action:  Verb such as ``install``, ``configure``, ``tls-enable``.
            product: Product or resource name (``dataiku``, ``nexus``, ``cluster``).
            context: Context name used for the operation.
            host:    Target host IP/hostname.
            params:  Key parameters worth recording (version, port, …).
            result:  Outcome — ``success`` or a short error description.
        """
        entry = {
            "timestamp": datetime.now(timezone.utc).isoformat(),
            "action": action,
            "product": product,
            "context": context,
            "host": host,
            "params": params or {},
            "result": result,
        }
        try:
            with open(self.history_path, "a", encoding="utf-8") as f:
                f.write(json.dumps(entry, ensure_ascii=False) + "\n")
        except OSError as e:
            logger.warning(f"Failed to write history entry: {e}")

    def read(self, *, limit: Optional[int] = None) -> List[Dict[str, Any]]:
        """Read operation history entries.

        Args:
            limit: If given, return only the *last* N entries.

        Returns:
            List of history entry dicts, oldest first.
        """
        if not self.history_path.exists():
            return []
        entries: List[Dict[str, Any]] = []
        try:
            with open(self.history_path, "r", encoding="utf-8") as f:
                for line in f:
                    line = line.strip()
                    if line:
                        try:
                            entries.append(json.loads(line))
                        except json.JSONDecodeError:
                            continue
        except OSError as e:
            logger.warning(f"Failed to read history: {e}")
            return []
        if limit is not None:
            entries = entries[-limit:]
        return entries
