"""Status files, PID management, stop-signal detection, and iteration journal."""

import datetime as dt
import json
import os
import time
from pathlib import Path
from typing import Dict, List, Optional

from project import get_project_description


def write_status(
    status_path: Path,
    project_id: str,
    iteration: int,
    phase: str,
    details: str,
    project_dir: Optional[Path] = None,
) -> None:
    """Write a human-readable status Markdown file."""
    ts = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    description = get_project_description(project_dir) if project_dir else ""
    desc_line = f"**Description:** {description}\n" if description else ""
    content = (
        f"# Loop Status — {project_id}\n\n"
        f"{desc_line}"
        f"**Updated:** {ts}\n"
        f"**Iteration:** {iteration}\n"
        f"**Phase:** {phase}\n\n"
        f"{details}\n"
    )
    try:
        status_path.parent.mkdir(parents=True, exist_ok=True)
        status_path.write_text(content, encoding="utf-8")
    except Exception:
        pass


def write_pid_file(project_dir: Path) -> None:
    pid_file = project_dir / ".autobuilder" / "daemon.pid"
    pid_file.parent.mkdir(parents=True, exist_ok=True)
    pid_file.write_text(str(os.getpid()) + "\n", encoding="utf-8")


def remove_pid_file(project_dir: Path) -> None:
    pid_file = project_dir / ".autobuilder" / "daemon.pid"
    try:
        pid_file.unlink()
    except OSError:
        pass


def check_stop_signal(project_dir: Path) -> bool:
    """Return ``True`` and delete the stop file if ``.autobuilder/stop`` exists."""
    stop_file = project_dir / ".autobuilder" / "stop"
    if stop_file.exists():
        try:
            stop_file.unlink()
        except OSError:
            pass
        return True
    return False


# ---------------------------------------------------------------------------
# Iteration journal — structured record of every iteration outcome
# ---------------------------------------------------------------------------

JOURNAL_FILENAME = "journal.jsonl"


def _journal_path(project_dir: Path) -> Path:
    return project_dir / ".autobuilder" / JOURNAL_FILENAME


def append_journal_entry(project_dir: Path, entry: Dict) -> None:
    """Append one JSON-lines entry to the iteration journal."""
    jpath = _journal_path(project_dir)
    jpath.parent.mkdir(parents=True, exist_ok=True)
    entry.setdefault("ts", int(time.time()))
    try:
        with open(jpath, "a", encoding="utf-8") as f:
            f.write(json.dumps(entry, separators=(",", ":")) + "\n")
    except Exception:
        pass


def load_journal(project_dir: Path, max_entries: int = 50) -> List[Dict]:
    """Load the last *max_entries* from the iteration journal.

    Returns an empty list on any I/O or parse error.  Malformed lines
    are silently skipped so a single corrupt line never blocks the daemon.
    """
    jpath = _journal_path(project_dir)
    if not jpath.exists():
        return []
    entries: List[Dict] = []
    try:
        for line in jpath.read_text(encoding="utf-8").splitlines():
            line = line.strip()
            if not line:
                continue
            try:
                entries.append(json.loads(line))
            except (json.JSONDecodeError, ValueError):
                continue
    except Exception:
        return []
    return entries[-max_entries:]
