"""
logger.py — Append-only JSONL task log.

Each completed tool invocation is recorded as one JSON line:
  {"ts": "...", "tool": "...", "args": {...}, "result": {...}, "duration_ms": N}

Import and use: from .logger import log_task
"""
from __future__ import annotations

import json
import time
from datetime import datetime
from pathlib import Path

from .config import LOG_DIR, TASK_LOG


def log_task(tool: str, args: dict, result: dict, duration_ms: float) -> None:
    """Append a single tool execution record to the JSONL task log."""
    try:
        LOG_DIR.mkdir(parents=True, exist_ok=True)
        record = {
            "ts": datetime.utcnow().isoformat(timespec="seconds") + "Z",
            "tool": tool,
            "args": _truncate_args(args),
            "result_keys": list(result.keys()),
            "error": result.get("error"),
            "duration_ms": round(duration_ms, 1),
        }
        with open(TASK_LOG, "a", encoding="utf-8") as f:
            f.write(json.dumps(record, ensure_ascii=False) + "\n")
    except Exception:
        pass  # Logging must never crash the agent


def _truncate_args(args: dict) -> dict:
    """Truncate large arg values before logging."""
    out = {}
    for k, v in args.items():
        if isinstance(v, str) and len(v) > 200:
            out[k] = v[:200] + "…"
        else:
            out[k] = v
    return out


def read_recent_tasks(n: int = 20) -> list[dict]:
    """Return the most recent N task log entries."""
    try:
        if not TASK_LOG.exists():
            return []
        lines = TASK_LOG.read_text(encoding="utf-8").splitlines()
        records = []
        for line in reversed(lines):
            line = line.strip()
            if line:
                try:
                    records.append(json.loads(line))
                except json.JSONDecodeError:
                    pass
            if len(records) >= n:
                break
        return records
    except Exception:
        return []
