from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path
from zoneinfo import ZoneInfo

from .config import client_dir


TZ = ZoneInfo("Europe/Warsaw")


def now_local() -> datetime:
    return datetime.now(TZ)


def append_history(domain: str, event: dict) -> Path:
    ts = now_local()
    event = {"timestamp": ts.isoformat(timespec="seconds"), **event}
    base = client_dir(domain) / "history"
    base.mkdir(parents=True, exist_ok=True)
    path = base / f"{ts.date().isoformat()}.jsonl"
    with path.open("a", encoding="utf-8") as f:
        f.write(json.dumps(event, ensure_ascii=False) + "\n")
    return path


def append_change_markdown(domain: str, title: str, rows: list[dict]) -> Path:
    ts = now_local()
    base = client_dir(domain) / "changes"
    base.mkdir(parents=True, exist_ok=True)
    path = base / f"{ts.date().isoformat()}.md"
    exists = path.exists()
    with path.open("a", encoding="utf-8") as f:
        if not exists:
            f.write(f"# Zmiany {ts.date().isoformat()}\n\n")
        f.write(f"## {ts.strftime('%H:%M')} - {title}\n\n")
        if not rows:
            f.write("Brak wdrozonych zmian.\n\n")
            return path
        keys = list(rows[0].keys())
        f.write("| " + " | ".join(keys) + " |\n")
        f.write("| " + " | ".join(["---"] * len(keys)) + " |\n")
        for row in rows:
            f.write("| " + " | ".join(str(row.get(k, "")) for k in keys) + " |\n")
        f.write("\n")
    return path

