#!/usr/bin/python3


from __future__ import annotations

import logging
from datetime import datetime
from pathlib import Path

from slpkg.config import config_load

logger = logging.getLogger(__name__)


class HistoryLogger:  # pylint: disable=[R0903]
    """Appends a structured one-line entry to the slpkg history log file."""

    def __init__(self) -> None:
        logger.debug("Initializing HistoryLogger.")
        self.history_log_file: Path = config_load.history_log_file
        logger.debug("HistoryLogger initialized. Log file: %s", self.history_log_file)

    def write(self, action: str, name: str, package: str, repository: str) -> None:
        """Append a history entry for a completed package operation.

        Args:
            action: Operation type — 'install', 'upgrade', 'reinstall', 'remove', 'build'.
            name: Package name (e.g. 'gnupg2').
            package: Full package filename (e.g. 'gnupg2-2.5.18-x86_64-1.txz').
            repository: Repository name (e.g. 'alien').
        """
        timestamp: str = datetime.now().strftime("%Y-%m-%d %H:%M")
        # Strip the file extension to get 'name-version-arch-build',
        # then remove the leading 'name-' prefix to isolate the version part.
        stem: str = Path(package).stem
        version: str = stem[len(name) + 1:] if stem.startswith(f"{name}-") else stem
        entry: str = f"{timestamp} | {action:<9} | {name:<30} | {version:<25} | {repository}\n"
        try:
            with self.history_log_file.open("a", encoding="utf-8") as f:
                f.write(entry)
            logger.debug("History entry written: %s", entry.strip())
        except OSError as e:
            logger.error("Failed to write history log '%s': %s", self.history_log_file, e)
