# Copyright (c) 2026 MergeGuide, Inc. All rights reserved.
# SPDX-License-Identifier: Proprietary
"""Session findings logger for MergeGuide hooks.

Appends structured findings to `.mergeguide/findings-log.jsonl` after each
hook execution. This log serves as:
- SOC 2 evidence (CC3.2 risk assessment, CC4.1 monitoring)
- Detection accuracy telemetry for triage workflows
"""

from __future__ import annotations

import fcntl
import json
import sys
from datetime import UTC, datetime
from pathlib import Path


def log_session_findings(
    violations: list,
    files_checked: list[str],
    hook_type: str,
    enforcement_mode: str,
    log_path: Path | None = None,
) -> None:
    """Append a findings entry to the JSONL log.

    Args:
        violations: List of Violation objects from the evaluation.
        files_checked: List of file paths that were checked.
        hook_type: Hook type (e.g., "pre-commit", "pre-push", "manual").
        enforcement_mode: Either "advisory" or "blocking".
        log_path: Override path for the log file. Defaults to
            `.mergeguide/findings-log.jsonl`.
    """
    if log_path is None:
        log_path = Path(".mergeguide/findings-log.jsonl")

    errors = sum(1 for v in violations if v.severity == "error")
    warnings = sum(1 for v in violations if v.severity == "warning")

    entry = {
        "timestamp": datetime.now(UTC).isoformat(),
        "hook_type": hook_type,
        "enforcement_mode": enforcement_mode,
        "files_checked": len(files_checked),
        "violations_total": len(violations),
        "violations_error": errors,
        "violations_warning": warnings,
    }

    try:
        log_path.parent.mkdir(parents=True, exist_ok=True)
        with open(log_path, "a") as f:
            fcntl.flock(f, fcntl.LOCK_EX)
            try:
                f.write(json.dumps(entry) + "\n")
            finally:
                fcntl.flock(f, fcntl.LOCK_UN)
    except OSError as e:
        print(f"[MergeGuide] Failed to write findings log: {e}", file=sys.stderr)
