"""
Logging Module - Audit trail for consolidation operations.

Contains:
- log_consolidation: Write consolidation report to log file
"""

import json
from pathlib import Path
from typing import Optional

from .models import ConsolidationReport


def log_consolidation(
    project: str,
    report: ConsolidationReport,
    log_dir: Optional[Path] = None
) -> None:
    """
    Log consolidation results to consolidation.log for audit trail.

    Args:
        project: Project name
        report: ConsolidationReport
        log_dir: Directory for log file (defaults to per-project logs dir)
    """
    if log_dir is None:
        from cli_utils import get_logs_dir
        log_dir = get_logs_dir(project)

    log_dir.mkdir(parents=True, exist_ok=True)
    log_file = log_dir / "consolidation.log"

    # Format log entry
    entry = {
        "timestamp": report.timestamp,
        "project": project,
        "clusters_found": report.clusters_found,
        "clusters_processed": report.clusters_processed,
        "consolidated": report.consolidated,
        "kept": report.kept,
        "deleted": report.deleted,
        "results": [r.to_dict() for r in report.results]
    }

    # Append to log file
    with open(log_file, "a", encoding="utf-8") as f:
        f.write(json.dumps(entry) + "\n")

    print(f"[Consolidate] Logged to {log_file}")
