#!/usr/bin/env python3
"""Gate Log — 门控执行日志记录器

每次门控检查的结果都追加到 deploy/gate_log.jsonl (JSON Lines)
每行一条记录，包含：时间戳、门控名、结果、详情

这个文件是用户审查AI是否偷懒的关键证据：
- 查看最近一次: tail -1 deploy/gate_log.jsonl | python -m json.tool
- 查看所有BLOCK: grep '"BLOCK"' deploy/gate_log.jsonl
- 查看某天: grep '2026-05-26' deploy/gate_log.jsonl
"""
import json
import os
from datetime import datetime, timezone

GATE_LOG = os.path.join(
    os.environ.get("NEXUS_DEPLOY_DIR", "/opt/nexus"),
    "deploy", "gate_log.jsonl"
)

def log_gate(gate_name: str, result: str, detail: str = "", files_checked: list = None):
    """Record a gate check result.

    Args:
        gate_name: e.g. "Changelog", "Audit", "Test", "Lint", "Import", "Security", "Review"
        result: "PASS", "BLOCK", "SKIP", "WARN"
        detail: Human-readable detail
        files_checked: List of files involved in this gate check
    """
    entry = {
        "ts": datetime.now(timezone.utc).isoformat(),
        "gate": gate_name,
        "result": result,
        "detail": detail,
    }
    if files_checked:
        entry["files"] = files_checked

    os.makedirs(os.path.dirname(GATE_LOG), exist_ok=True)
    with open(GATE_LOG, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry, ensure_ascii=False) + "\n")

if __name__ == "__main__":
    import sys
    if len(sys.argv) >= 3:
        log_gate(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) > 3 else "")
    else:
        # Print recent log
        if os.path.exists(GATE_LOG):
            with open(GATE_LOG, encoding="utf-8") as f:
                lines = f.readlines()[-20:]
            for line in lines:
                d = json.loads(line)
                icon = {"PASS": "✅", "BLOCK": "🚫", "SKIP": "⏭️", "WARN": "⚠️"}.get(d["result"], "?")
                print(f"{d['ts'][:19]} {icon} {d['gate']}: {d.get('detail','')}")
        else:
            print("No gate log found")
