"""배치 메타·셀렉터 확장."""
from __future__ import annotations

import json
import os
import secrets
from datetime import datetime, timezone
from pathlib import Path
from typing import List, Optional

from .listing import list_runs
from .json_boundary import write_owned_object_atomic
from .resolver import resolve_last, resolve_run_id


def make_batch_id() -> str:
    """20260505T143012-a1b2c3 형식 배치 ID."""
    ts = datetime.now(timezone.utc).replace(tzinfo=None).strftime("%Y%m%dT%H%M%S")
    return f"{ts}-{secrets.token_hex(3)}"


def write_batch_meta(home: Path, batch_id: str, payload: dict) -> Path:
    target = home / "batches" / f"{batch_id}.json"
    write_owned_object_atomic(target, payload, artifact="batch metadata")
    return target


def expand_selectors(home: Path, *, explicit: List[str], use_filter: bool,
                     project: str, task_group: str, status: str, since: str,
                     last: bool, from_stdin: bool,
                     stdin_data: Optional[str] = None) -> List[str]:
    """selector 들을 평탄화해 runId 목록을 반환. 중복 제거. 결정적 순서.
    stdin_data: 호출자가 미리 읽어 전달한 stdin 페이로드. 자식 프로세스의
    sys.stdin 이 heredoc 등으로 가려진 경우 caller 가 채워준다.
    """
    import sys as _sys
    ids: List[str] = []
    seen = set()

    def add(rid: str) -> None:
        if rid not in seen:
            seen.add(rid); ids.append(rid)

    if last:
        add(resolve_last(home, project=project, task_group=task_group))
    if use_filter:
        rows = list_runs(home, project=project, task_group=task_group,
                         status=status, since=since, include_archive=True)
        for r in rows:
            add(r["runId"])
    if from_stdin:
        source = (stdin_data.splitlines() if stdin_data is not None
                  else _sys.stdin)
        for line in source:
            line = line.strip()
            if line:
                add(resolve_run_id(home, line))
    for q in explicit:
        add(resolve_run_id(home, q))
    return ids
