"""Logging backend — writes to a local file for MVP, swap for API/DB later."""

import json
import os
import uuid
from datetime import datetime, timezone
from pathlib import Path


_LOG_FILE = Path(
    os.environ.get(
        "BLUEALPHA_LOG_FILE",
        str(Path.home() / ".bluealpha" / "session.log"),
    )
)


def _write(label: str, data: dict) -> str:
    """Append a record to the log file. Returns the generated ID."""
    record_id = str(uuid.uuid4())
    data["id"] = record_id
    data["created_at"] = datetime.now(timezone.utc).isoformat()

    header = f"\n=== {label} [{data['created_at']}] ===\n"
    _LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
    with open(_LOG_FILE, "a") as f:
        f.write(header + json.dumps(data, indent=2, default=str) + "\n")

    return record_id


def save_session_log(data: dict) -> str:
    return _write("SESSION LOG", data)


def save_decision(data: dict) -> str:
    return _write("DECISION SAVED", data)


def save_strategy_task(data: dict) -> str:
    return _write("STRATEGY TASK QUEUED", data)
