"""
reproducibility_proof/audit_log.py

Maintains a persistent audit trail of every verification run.
Appends one JSONL record per verification attempt to .marco/verification_log.jsonl
"""
import json
import os
import platform
import sys
from datetime import datetime, timezone
from pathlib import Path


def _get_environment_snapshot() -> dict:
    """Capture the current runtime environment for comparison."""
    import importlib.metadata
    env = {
        'python_version': sys.version,
        'platform': platform.platform(),
        'os': os.name,
    }
    for pkg in ('numpy', 'pandas'):
        try:
            env[f'{pkg}_version'] = importlib.metadata.version(pkg)
        except Exception:
            env[f'{pkg}_version'] = 'unknown'
    return env


def append_audit_entry(marco_dir: Path, version_id: str, result: str, details: dict):
    """
    Append a single verification audit record to .marco/verification_log.jsonl

    Args:
        marco_dir:  Path to the .marco directory.
        version_id: The version hash that was verified.
        result:     'PASS' or 'FAIL'.
        details:    Any extra info (stored_hash, computed_hash, etc.)
    """
    log_path = marco_dir / 'verification_log.jsonl'
    entry = {
        'timestamp': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
        'version_id': version_id,
        'result': result,
        'environment': _get_environment_snapshot(),
        **details,
    }
    with open(log_path, 'a', encoding='utf-8') as f:
        f.write(json.dumps(entry) + '\n')


def read_audit_log(marco_dir: Path) -> list:
    """Read and return all audit log entries as a list of dicts."""
    log_path = marco_dir / 'verification_log.jsonl'
    if not log_path.exists():
        return []
    entries = []
    with open(log_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if line:
                try:
                    entries.append(json.loads(line))
                except json.JSONDecodeError:
                    pass
    return entries
