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

import os
import pathlib
import sys

from typing import List, Union  # noqa: H301

from . import defs


def test_tinydns_edit(cfg: defs.Config, tempd: pathlib.Path) -> None:
    """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[Union[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: "
                f"{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:
            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="")
