"""v3.6 Runtime Harness — append-only JSONL decision logger.

chair_authorization_id=CHAIR-AUTH-TASK-2703-V36-HARNESS-MVP-260528

Design:
- Append-only; never truncates or rewrites.
- Fail-safe: any exception is silently swallowed — logger must NEVER raise.
- ALLOW decisions only recorded when env V36_HARNESS_LOG_ALLOW=1.
- Test isolation: when env ANU_V36_HARNESS_TEST_MODE=1, writes to /tmp/v36_harness_decision_test.jsonl.
"""
from __future__ import annotations

import json
import os

CHAIR_AUTHORIZATION_ID = "CHAIR-AUTH-TASK-2703-V36-HARNESS-MVP-260528"

_PRODUCTION_JSONL = "/home/jay/workspace/memory/system/.v36_harness_decision.jsonl"
_TEST_JSONL = "/tmp/v36_harness_decision_test.jsonl"


def _jsonl_path() -> str:
    if os.environ.get("ANU_V36_HARNESS_TEST_MODE", "") == "1":
        return _TEST_JSONL
    return _PRODUCTION_JSONL


def log_decision(decision_record: dict) -> None:
    """Append a decision record to the JSONL audit log.

    Args:
        decision_record: dict with at minimum keys: ts, decision, matched_rule,
                         command_or_tool, task_id, timestamp.

    Silently swallows all exceptions (fail-safe contract).
    ALLOW decisions are only written when V36_HARNESS_LOG_ALLOW=1.
    """
    try:
        decision = decision_record.get("decision", "")

        # Skip ALLOW unless explicitly requested (disk accumulation guard)
        if decision == "ALLOW":
            if os.environ.get("V36_HARNESS_LOG_ALLOW", "") != "1":
                return

        # Ensure chair_authorization_id is always injected
        record = dict(decision_record)
        record.setdefault("chair_authorization_id", CHAIR_AUTHORIZATION_ID)

        path = _jsonl_path()
        os.makedirs(os.path.dirname(path) if os.path.dirname(path) else ".", exist_ok=True)
        with open(path, "a", encoding="utf-8") as fh:
            fh.write(json.dumps(record, ensure_ascii=False) + "\n")
    except Exception:
        # Absolute fail-safe: never raise from logger
        pass
