"""Test the `tinydns-edit` tool and the generated data file."""

from __future__ import annotations

import os
import sys
import typing

from . import defs


if typing.TYPE_CHECKING:
    import pathlib


# This function may be simplified in varous ways with later versions of Python
def test_tinydns_edit(cfg: defs.Config, tempd: pathlib.Path) -> None:  # noqa: C901
    """Test the operation of `tinydns-edit`."""
    print("\n==== test_tinydns_edit")

    data = tempd / "data"
    data_temp = data.with_suffix(".tmp")
    for chk in (data, data_temp):
        if chk.exists():
            sys.exit(f"Did not expect {chk} to exist")

    tedit = cfg.sbindir / "tinydns-edit"
    if not tedit.is_file() or not os.access(tedit, os.X_OK):
        sys.exit(f"Not an executable file: {tedit}")

    data.write_text("", encoding=defs.MINENC)
    old_lines: list[str] = []

    for idx, rec in enumerate(defs.RECORDS):
        cfg.diag(f"- {idx}: {rec}")
        cmd: list[pathlib.Path | str] = [
            tedit,
            data,
            data_temp,
            "add",
            rec.rtype,
            rec.name,
            rec.address,
        ]
        cfg.diag("  - " + " ".join(map(str, cmd)))

        outp = cfg.check_output(cmd)
        if outp:
            sys.exit(f"{cmd!r} produced output: {outp!r}")
        if data_temp.exists():
            sys.exit(f"{cmd!r} left {data_temp}")
        if not data.exists():
            sys.exit(f"{cmd!r} removed {data}")

        lines = data.read_text(encoding=defs.MINENC).splitlines()
        if len(lines) != idx + 1:
            sys.exit(f"{cmd!r} left {len(lines)} instead of {idx + 1} lines: {lines!r}")
        if lines[:-1] != old_lines:
            sys.exit(f"{cmd!r} did not preserve {old_lines!r}: {lines!r}")

        line = lines[-1]
        fields = line.split(":")
        if len(fields) < 3:  # noqa: PLR2004  # this may be better with py310 `match`/`case`
            sys.exit(f"{cmd!r} added a short line: {line!r}")
        exp = defs.TYPES[rec.rtype].prefix + rec.name
        if fields[0] != exp:
            sys.exit(f"{cmd!r} added an unexpected line: {line!r}")
        if rec.address not in fields[1:]:
            sys.exit(f"{cmd!r} added a line with no {rec.address!r}: {line!r}")

        old_lines.append(line)

    print("After the tinydns-edit test the contents of the data file is:")
    print(data.read_text(encoding=defs.MINENC), end="")
