"""Helper functions for parsing Copilot CLI session files (JSONL + YAML)."""

from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import yaml
from loguru import logger


def parse_jsonl(path: Path) -> list[dict[str, Any]]:
    """Read a .jsonl file and parse each non-empty line as JSON.

    Empty lines are skipped. Lines that fail to parse as JSON are logged as
    warnings and skipped.
    """
    records: list[dict[str, Any]] = []
    try:
        text = path.read_text(encoding="utf-8")
    except OSError as exc:
        logger.warning("Failed to read JSONL file {}: {}", path, exc)
        return records

    for lineno, raw in enumerate(text.splitlines(), start=1):
        stripped = raw.strip()
        if not stripped:
            continue
        try:
            import json

            records.append(json.loads(stripped))
        except (json.JSONDecodeError, ValueError) as exc:
            logger.warning("Skipping unparseable JSON line {} in {}: {}", lineno, path, exc)
            continue
    return records


def parse_workspace_yaml(path: Path) -> dict[str, Any] | None:
    """Parse a workspace.yaml file using yaml.safe_load.

    Returns None if the file is missing or cannot be parsed (a warning is
    logged in those cases).
    """
    if not path.exists():
        logger.debug("workspace.yaml not found at {}", path)
        return None
    try:
        with path.open("r", encoding="utf-8") as fh:
            data = yaml.safe_load(fh)
    except (yaml.YAMLError, OSError) as exc:
        logger.warning("Failed to parse workspace.yaml at {}: {}", path, exc)
        return None
    if data is None:
        return None
    if not isinstance(data, dict):
        logger.warning("workspace.yaml at {} did not contain a mapping", path)
        return None
    return data


def parse_datetime(value: str | None) -> datetime:
    """Parse an ISO 8601 timestamp, handling a trailing 'Z' suffix.

    Falls back to ``datetime.now(UTC)`` when the value is missing or cannot be
    parsed.
    """
    if not value:
        return datetime.now(UTC)
    try:
        cleaned = value.strip()
        if cleaned.endswith("Z"):
            cleaned = cleaned[:-1] + "+00:00"
        return datetime.fromisoformat(cleaned)
    except (ValueError, TypeError) as exc:
        logger.warning("Failed to parse datetime {!r}: {}", value, exc)
        return datetime.now(UTC)
