# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Query logging — append brain queries to the query log file."""

import json
from pathlib import Path

# brain_query/ -> brain/ -> pulse/ -> ROOT
_ROOT_DIR = Path(__file__).resolve().parent.parent.parent.parent
QUERY_LOG_FILE = _ROOT_DIR / "state" / "brain_query_log.json"


def _log_query(query: str, result_count: int) -> None:
    """Append query to brain_query_log.json (last 100). File-locked for concurrency safety."""
    try:
        from datetime import datetime, timezone
        from pulse.core.brain_io import _acquire
        QUERY_LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
        with _acquire(QUERY_LOG_FILE):
            entries = []
            if QUERY_LOG_FILE.exists():
                try:
                    entries = json.loads(QUERY_LOG_FILE.read_text(encoding="utf-8"))
                    if not isinstance(entries, list):
                        entries = []
                except Exception:
                    entries = []
            entries.append({"query": query[:200], "results": result_count,
                            "timestamp": datetime.now(timezone.utc).isoformat()})
            QUERY_LOG_FILE.write_text(json.dumps(entries[-100:], indent=2), encoding="utf-8")
    except Exception:
        pass
