from __future__ import annotations

import json
from pathlib import Path


def merge_atoms_jsonl(local_path: Path, remote_bytes: bytes) -> None:
    """append-only 合并，按 id 去重。"""
    local_rows: dict[str, dict] = {}
    if local_path.is_file():
        with local_path.open(encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue
                row = json.loads(line)
                local_rows[row["id"]] = row

    for line in remote_bytes.decode("utf-8").splitlines():
        line = line.strip()
        if not line:
            continue
        row = json.loads(line)
        local_rows.setdefault(row["id"], row)

    ordered = sorted(local_rows.values(), key=lambda r: r.get("created_at", ""))
    local_path.parent.mkdir(parents=True, exist_ok=True)
    with local_path.open("w", encoding="utf-8") as f:
        for row in ordered:
            f.write(json.dumps(row, ensure_ascii=False) + "\n")


def merge_json_dict(local_path: Path, remote_bytes: bytes) -> None:
    """JSON dict：比较条目 updated_at，新者胜。"""
    local: dict = {}
    if local_path.is_file():
        local = json.loads(local_path.read_text(encoding="utf-8"))

    remote = json.loads(remote_bytes.decode("utf-8"))
    if not isinstance(remote, dict):
        return

    for key, remote_val in remote.items():
        if not isinstance(remote_val, dict):
            local[key] = remote_val
            continue
        local_val = local.get(key)
        if not isinstance(local_val, dict):
            local[key] = remote_val
            continue
        remote_ts = remote_val.get("updated_at", "")
        local_ts = local_val.get("updated_at", "")
        if remote_ts >= local_ts:
            local[key] = remote_val

    local_path.parent.mkdir(parents=True, exist_ok=True)
    local_path.write_text(
        json.dumps(local, ensure_ascii=False, indent=2) + "\n",
        encoding="utf-8",
    )
