"""Persistent tool-error tracker for drive discovery."""
from __future__ import annotations

import json
import os
from datetime import datetime, timedelta

from persistence import secure_atomic_write


def _workspace() -> str:
    from core import get_workspace_path
    return get_workspace_path()


def _path() -> str:
    return os.path.join(_workspace(), "memory", "tool_errors.json")


def _read() -> list[dict]:
    path = _path()
    if not os.path.isfile(path):
        return []
    try:
        with open(path, "r", encoding="utf-8") as f:
            data = json.load(f)
        return data if isinstance(data, list) else []
    except Exception:
        return []


def _write(rows: list[dict]) -> None:
    path = _path()
    os.makedirs(os.path.dirname(path), exist_ok=True)
    secure_atomic_write(path, json.dumps(rows, indent=2, ensure_ascii=True))
    try:
        os.chmod(path, 0o600)
    except OSError:
        pass


def record_tool_error(tool_name: str, error_message: str, max_rows: int = 100) -> None:
    """Append a tool error row to memory/tool_errors.json."""
    rows = _read()
    rows.append(
        {
            "ts": datetime.utcnow().replace(microsecond=0).isoformat(),
            "tool": (tool_name or "").strip(),
            "error": (error_message or "").strip()[:500],
        }
    )
    if len(rows) > max_rows:
        rows = rows[-max_rows:]
    _write(rows)


def get_error_patterns(days: int = 7, min_count: int = 3) -> list[dict]:
    """Return repeated error patterns by tool in the last N days."""
    rows = _read()
    if not rows:
        return []
    cutoff = datetime.utcnow() - timedelta(days=max(1, int(days)))
    grouped: dict[str, list[dict]] = {}
    for row in rows:
        if not isinstance(row, dict):
            continue
        tool = str(row.get("tool") or "").strip()
        if not tool:
            continue
        try:
            ts = datetime.fromisoformat(str(row.get("ts") or ""))
        except Exception:
            continue
        if ts < cutoff:
            continue
        grouped.setdefault(tool, []).append(row)
    out: list[dict] = []
    for tool, items in grouped.items():
        if len(items) >= int(min_count):
            out.append(
                {
                    "tool": tool,
                    "count": len(items),
                    "last_error": str(items[-1].get("error") or ""),
                }
            )
    out.sort(key=lambda x: int(x.get("count", 0)), reverse=True)
    return out
