# Copyright (C) 2026 GoodData Corporation

"""Logging helpers for command runner utilities."""

from __future__ import annotations

import re
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

from aida_mcp.utils.artifacts import get_artifacts_root

LOG_ROOT = get_artifacts_root() / "logs"


def write_command_log(
    cmd: list[str],
    cwd: Path,
    stdout: str,
    stderr: str,
    exit_code: int,
) -> Path | None:
    now = datetime.now(UTC)
    timestamp = now.strftime("%Y%m%d-%H%M%S-%f")
    command_name = Path(cmd[0]).name if cmd else "command"
    slug = _slugify(command_name)
    log_dir = LOG_ROOT / now.strftime("%Y%m%d")
    try:
        log_dir.mkdir(parents=True, exist_ok=True)
    except OSError:
        return None

    log_path = log_dir / f"{timestamp}-{slug}.log"
    header = [
        f"Timestamp: {now.isoformat()}",
        f"Command: {' '.join(cmd)}",
        f"CWD: {cwd}",
        f"Exit Code: {exit_code}",
        "",
        "--- stdout ---",
        stdout.rstrip() or "<empty>",
        "",
        "--- stderr ---",
        stderr.rstrip() or "<empty>",
        "",
    ]
    try:
        log_path.write_text("\n".join(header), encoding="utf-8")
    except OSError:
        return None
    return log_path


def open_streaming_log(cmd: list[str], cwd: Path) -> tuple[Path | None, Any]:
    now = datetime.now(UTC)
    timestamp = now.strftime("%Y%m%d-%H%M%S-%f")
    command_name = Path(cmd[0]).name if cmd else "command"
    slug = _slugify(command_name)
    log_dir = LOG_ROOT / now.strftime("%Y%m%d")
    try:
        log_dir.mkdir(parents=True, exist_ok=True)
    except OSError:
        return None, None

    log_path = log_dir / f"{timestamp}-{slug}.log"
    try:
        handle = log_path.open("w", encoding="utf-8")
        handle.write(f"Timestamp: {now.isoformat()}\n")
        handle.write(f"Command: {' '.join(cmd)}\n")
        handle.write(f"CWD: {cwd}\n")
        handle.write("Exit Code: <pending>\n\n")
        return log_path, handle
    except OSError:
        return None, None


def write_stream_log_line(handle: Any, stream_name: str, line: str) -> None:
    if handle is None:
        return
    try:
        handle.write(f"[{stream_name}] {line}\n")
    except OSError:
        return


def finalize_stream_log(handle: Any, exit_code: int) -> None:
    if handle is None:
        return
    try:
        handle.write(f"\nExit Code: {exit_code}\n")
        handle.flush()
        handle.close()
    except OSError:
        return


def _slugify(value: str) -> str:
    normalized = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-")
    return normalized or "command"
