# _St 기준 상대경로: ..\AutoDistribute\test_autodistribute.py
from __future__ import annotations

import tempfile
import zipfile
from pathlib import Path

from AutoDistribute import build_st_zip, validate_zip


def _write(path: Path, text: str = "x") -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(text, encoding="utf-8")


def test_build_excludes_runtime_and_read_docs() -> None:
    with tempfile.TemporaryDirectory() as td:
        root = Path(td)
        st = root / "_St"
        _write(st / "Auto8700" / "main.py", "print('ok')")
        _write(st / "Auto8700" / "ai_read.md")
        _write(st / "Auto8700" / "read_note.txt")
        _write(st / "Auto8700" / "logs" / "run.log")
        _write(st / "Shared" / "data" / "state.sqlite3")
        _write(st / "Shared" / "__pycache__" / "a.cpython-313.pyc")
        _write(st / "Shared" / ".pytest_cache" / "x")
        _write(st / "Shared" / "keep.json", "{}")

        output = root / "_St.zip"
        stats = build_st_zip(st, output)
        assert stats.included_files == 2

        with zipfile.ZipFile(output) as zf:
            names = set(zf.namelist())
        assert names == {"_St/Auto8700/main.py", "_St/Shared/keep.json"}

        count, violations = validate_zip(output)
        assert count == 2
        assert violations == []


def test_output_root_is_st() -> None:
    with tempfile.TemporaryDirectory() as td:
        root = Path(td)
        st = root / "_St"
        _write(st / "IG_StYellow" / "manifest.json", "{}")
        output = root / "_St.zip"
        build_st_zip(st, output)
        with zipfile.ZipFile(output) as zf:
            assert all(name.startswith("_St/") for name in zf.namelist())


def test_validate_rejects_read_document() -> None:
    with tempfile.TemporaryDirectory() as td:
        output = Path(td) / "bad.zip"
        with zipfile.ZipFile(output, "w") as zf:
            zf.writestr("_St/read_internal.md", "x")
        _, violations = validate_zip(output)
        assert any("read 문서 포함" in item for item in violations)
