"""Obsidian vault daily digest writer."""

from __future__ import annotations

import logging
from datetime import datetime, timezone
from pathlib import Path

logger = logging.getLogger(__name__)


async def write_daily_digest(
    vault_path: str,
    project_name: str,
    summary: str,
    status_counts: dict,
    escalations: list[dict],
) -> str:
    """Write a daily digest markdown file to the Obsidian vault.

    File: {vault_path}/Loom/{date}-{project_name}.md

    Returns the file path written.
    """
    import asyncio

    today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
    safe_name = project_name.replace(" ", "-").lower()
    loom_dir = Path(vault_path) / "Loom"

    def _write() -> str:
        loom_dir.mkdir(parents=True, exist_ok=True)
        file_path = loom_dir / f"{today}-{safe_name}.md"

        lines = [
            f"# Loom Daily Digest — {project_name}",
            f"**Date:** {today}",
            "",
            "## Summary",
            summary or "No summary available.",
            "",
            "## Status Breakdown",
        ]

        if status_counts:
            for status, count in sorted(status_counts.items()):
                lines.append(f"- **{status.capitalize()}:** {count}")
        else:
            lines.append("- No status data available.")

        lines.append("")
        lines.append("## Escalations")

        if escalations:
            for esc in escalations:
                task_id = esc.get("task_id", "unknown")
                message = esc.get("message", "No message")
                lines.append(f"- `{task_id}`: {message}")
        else:
            lines.append("- No open escalations.")

        lines.append("")
        lines.append("---")
        lines.append("*Generated by Loom Orchestrator*")
        lines.append("")

        file_path.write_text("\n".join(lines))
        logger.info("Wrote daily digest to %s", file_path)
        return str(file_path)

    loop = asyncio.get_running_loop()
    return await loop.run_in_executor(None, _write)
