from __future__ import annotations

import json
from datetime import UTC, datetime
from typing import Any


def now_iso(*, use_utc: bool = True, tz_name: str | None = None) -> dict[str, Any]:
    if tz_name:
        try:
            from zoneinfo import ZoneInfo

            tz = ZoneInfo(tz_name)
        except Exception as e:
            return {"ok": False, "error": f"invalid timezone: {e}"}
        dt = datetime.now(tz)
        return {"ok": True, "iso": dt.isoformat(), "timezone": tz_name}
    if use_utc:
        dt = datetime.now(UTC)
        return {"ok": True, "iso": dt.isoformat(), "timezone": "UTC"}
    dt = datetime.now().astimezone()
    return {"ok": True, "iso": dt.isoformat(), "timezone": str(dt.tzinfo)}


def _parse_iso(s: str) -> datetime:
    s = s.strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    return datetime.fromisoformat(s)


def elapsed_ms(start_iso: str, end_iso: str) -> dict[str, Any]:
    try:
        a = _parse_iso(start_iso)
        b = _parse_iso(end_iso)
    except ValueError as e:
        return {"ok": False, "error": f"invalid iso timestamp: {e}"}
    delta = b - a
    ms = int(delta.total_seconds() * 1000)
    return {"ok": True, "duration_ms": ms}


def log_record(
    level: str,
    message: str,
    **fields: Any,
) -> dict[str, Any]:
    rec: dict[str, Any] = {
        "level": level,
        "message": message,
        **fields,
    }
    now = now_iso(use_utc=True)
    if now.get("ok"):
        rec["ts"] = now["iso"]
    return {"ok": True, "record": rec}


def append_jsonl(path: str, record: dict[str, Any]) -> dict[str, Any]:
    line = json.dumps(record, ensure_ascii=False) + "\n"
    with open(path, "a", encoding="utf-8") as f:
        f.write(line)
    return {"ok": True, "path": path, "bytes": len(line.encode("utf-8"))}


def run_operation(operation: str, payload: dict[str, Any]) -> dict[str, Any]:
    op = operation.strip().lower()
    if op == "now_iso":
        return now_iso(
            use_utc=bool(payload.get("use_utc", True)),
            tz_name=payload.get("timezone") or None,
        )
    if op == "elapsed_ms":
        return elapsed_ms(
            str(payload.get("start_iso") or ""),
            str(payload.get("end_iso") or ""),
        )
    if op == "log_record":
        msg = str(payload.get("message") or "")
        lvl = str(payload.get("level") or "info")
        extra = {k: v for k, v in payload.items() if k not in ("message", "level", "operation")}
        return log_record(lvl, msg, **extra)
    return {"ok": False, "error": f"unknown operation: {operation}"}
