"""Tests for script execution MySQL persist compaction."""

import json

from server.infrastructure.redis.script_execution_store import (
    MYSQL_RESULTS_SOFT_LIMIT_BYTES,
    PERSIST_STDIO_MAX_CHARS,
    compact_results_for_mysql_persist,
    pack_mysql_results_blob,
)


def test_compact_truncates_long_stdio():
    results = {
        "1": {
            "status": "success",
            "exit_code": 0,
            "stdout": "x" * 2000,
            "stderr": "y" * 100,
        },
    }
    compact = compact_results_for_mysql_persist(results)
    assert len(compact["1"]["stdout"]) <= PERSIST_STDIO_MAX_CHARS
    assert compact["1"]["stdout_truncated"] is True
    assert compact["1"]["stderr"] == "y" * 100


def test_pack_mysql_fits_large_batch_like_production():
    """366 servers with mysql warning stderr — must fit under old TEXT limit after compact."""
    results = {
        str(i): {
            "status": "success" if i <= 256 else "failed",
            "exit_code": 0 if i <= 256 else 1,
            "stdout": "",
            "stderr": "mysql: [Warning] Using a password on the command line interface can be insecure.\n",
        }
        for i in range(1, 367)
    }
    blob = pack_mysql_results_blob(results, [{"action": "execution_finished", "detail": "ok"}])
    assert len(blob.encode("utf-8")) < 65535


def test_pack_mysql_under_soft_limit_for_huge_output():
    results = {
        str(i): {
            "status": "failed",
            "exit_code": 1,
            "stdout": "line\n" * 500,
            "stderr": "err\n" * 500,
        }
        for i in range(1, 401)
    }
    blob = pack_mysql_results_blob(results, [])
    assert len(blob.encode("utf-8")) <= MYSQL_RESULTS_SOFT_LIMIT_BYTES
    data = json.loads(blob)
    assert data["1"].get("persist_summary_only") or data["1"].get("stdout_truncated")
