#!/usr/bin/env python3
"""Contract for the standard MMC READ DVD STRUCTURE CDB boundary."""

from __future__ import annotations

import argparse
from pathlib import Path


def require(text: str, token: str, label: str) -> None:
    if token not in text:
        raise SystemExit(f"FAIL: missing {label}: {token}")
    print(f"PASS: {label}")


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--source-root",
        type=Path,
        default=Path(__file__).resolve().parents[1],
    )
    args = parser.parse_args()

    source_root = args.source_root.resolve()
    dvd_drive = (
        source_root / "libfriidump" / "dvd_drive.c"
    ).read_text(encoding="utf-8")
    windows_utils = (
        source_root / "libfriidump" / "xbox_ref" / "utils.c"
    ).read_text(encoding="utf-8")
    dumper = (
        source_root / "libfriidump" / "dumper.c"
    ).read_text(encoding="utf-8")

    start = dvd_drive.index("int dvd_read_dvd_structure")
    end = dvd_drive.index("\n}\n", start) + 3
    function = dvd_drive[start:end]

    require(
        function,
        "mmc.cmd[6] = layer;",
        "READ DVD STRUCTURE layer is CDB byte 6",
    )
    require(
        function,
        "mmc.cmd[7] = format;",
        "READ DVD STRUCTURE format is CDB byte 7",
    )
    require(
        function,
        "mmc.cmd[8] = (u_int8_t) ((extbufsize & 0xFF00) >> 8);",
        "allocation length high byte is CDB byte 8",
    )
    require(
        function,
        "mmc.cmd[9] = (u_int8_t)  (extbufsize & 0x00FF);",
        "allocation length low byte is CDB byte 9",
    )
    require(
        function,
        "mmc.cmdlen = 12;",
        "READ DVD STRUCTURE uses a 12-byte CDB",
    )

    if "mmc.cmd[11] = format;" in function:
        raise SystemExit(
            "FAIL: READ DVD STRUCTURE format is still written to control byte 11"
        )
    print("PASS: READ DVD STRUCTURE control byte 11 is not used as Format")

    require(
        windows_utils,
        "sptd.Cdb[7] = 0x04;",
        "copied Windows DMI request uses format byte 7",
    )
    require(
        dumper,
        "[XBOX-DVD-STRUCTURE] format=0x04 name=DMI cdb_format_byte=7 result=%s",
        "persistent DMI capture diagnostic",
    )

    print("XBOX READ DVD STRUCTURE CDB CONTRACT: PASS")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
