"""`clean RUN_ID` のサーバの出力（NUL 区切りの記録）と判定の入力を組み立てる補助.

SPEC_03「clean」．

`build_clean_list_command` がサーバで出す形を，目印の定数から組み立てる．`tests/test_cleanup.py`
（解析・判定）と `tests/test_cli.py`（サブコマンドの流れ）が使う．名前は架空のものだけを使う．
"""

from __future__ import annotations

import hashlib
from collections.abc import Sequence

from ls_helpers import Record, encode_records

from labremote.commands import (
    CLEAN_AFTER_PREFIX,
    CLEAN_BEGIN_MARKER,
    CLEAN_END_MARKER,
    CLEAN_FILE_PREFIX,
    CLEAN_FIND_RC_PREFIX,
    CLEAN_NOHASH_PREFIX,
    CLEAN_OTHER_PREFIX,
    CLEAN_RUN_PREFIX,
    CLEAN_STATE_PRESENT,
)
from labremote.config import ResultsConfig

CLEAN_RUN_ID = "20261119-120000_demo_abc1234"

# clean の判定のテストで使う設定の results（discard を含む）
CLEAN_RESULTS_DICT = {
    "pull": {
        "files": ["config.yaml", "metrics.json"],
        "dirs": [{"path": "figures", "suffix": ".png"}],
    },
    "checkpoints": {"dir": "checkpoints", "files": ["best.pth"]},
    "discard": {
        "files": ["cache.bin", "nohup.out"],
        "dirs": [
            {"path": "debug", "suffix": ".png"},
            {"path": "tmp/vis", "suffix": ".jpg"},
        ],
    },
}
CLEAN_RESULTS = ResultsConfig.model_validate(CLEAN_RESULTS_DICT)

CLEAN_RESULTS_YAML = """\
results:
  pull:
    files: [config.yaml, metrics.json]
    dirs:
      - path: figures
        suffix: .png
  checkpoints:
    dir: checkpoints
    files: [best.pth]
  discard:
    files: [cache.bin, nohup.out]
    dirs:
      - path: debug
        suffix: .png
      - path: tmp/vis
        suffix: .jpg
"""


def sha(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def _b(value: Record) -> bytes:
    return value if isinstance(value, bytes) else value.encode("utf-8")


def file_record(rel: Record, data: bytes = b"x", *, run_id: str = CLEAN_RUN_ID) -> bytes:
    """`file <バイト数> <sha256> ./<RUN_ID>/<rel>` の記録（大きさとハッシュは data から）."""
    head = f"{CLEAN_FILE_PREFIX}{len(data)} {sha(data)} ./{run_id}/".encode()
    return head + _b(rel)


def raw_file_record(size: str, digest: str, path: Record) -> bytes:
    """欄を自由に書いた file の記録（path は `./<RUN_ID>/...` を含めて書く）."""
    return f"{CLEAN_FILE_PREFIX}{size} {digest} ".encode() + _b(path)


def other_record(rel: Record, *, run_id: str = CLEAN_RUN_ID) -> bytes:
    return f"{CLEAN_OTHER_PREFIX}./{run_id}/".encode() + _b(rel)


def nohash_record(rel: Record, *, run_id: str = CLEAN_RUN_ID) -> bytes:
    return f"{CLEAN_NOHASH_PREFIX}./{run_id}/".encode() + _b(rel)


def clean_records(
    entries: Sequence[Record] = (),
    *,
    find_rc: int | str = 0,
    after: str = CLEAN_STATE_PRESENT,
) -> list[Record]:
    """実験フォルダが present のときの記録の並び."""
    return [
        CLEAN_BEGIN_MARKER,
        CLEAN_RUN_PREFIX + CLEAN_STATE_PRESENT,
        *entries,
        f"{CLEAN_FIND_RC_PREFIX}{find_rc}",
        CLEAN_AFTER_PREFIX + after,
        CLEAN_END_MARKER,
    ]


def clean_output(entries: Sequence[Record] = (), **kwargs: object) -> bytes:
    return encode_records(clean_records(entries, **kwargs))  # type: ignore[arg-type]


def clean_state_output(state: str) -> bytes:
    """実験フォルダが present でないときの出力."""
    return encode_records([CLEAN_BEGIN_MARKER, CLEAN_RUN_PREFIX + state, CLEAN_END_MARKER])
