from __future__ import annotations

from pathlib import Path
import subprocess

import pytest

from asm3042_flasher.device import FlasherError
from asm3042_flasher.flashrom_backend import FlashromConfig, default_backup_path, read_flash, write_flash


def test_default_backup_path() -> None:
    assert default_backup_path("/tmp/fw.bin") == Path("/tmp/fw.backup.bin")


def test_read_flash_builds_expected_command(monkeypatch) -> None:
    calls: list[list[str]] = []

    def fake_run(command, check):
        calls.append(command)
        assert check is True
        return None

    monkeypatch.setattr(subprocess, "run", fake_run)

    read_flash("/tmp/backup.bin", config=FlashromConfig(programmer="ch341a_spi"))

    assert calls == [["flashrom", "-p", "ch341a_spi", "-r", "/tmp/backup.bin"]]


def test_write_flash_builds_expected_command(monkeypatch) -> None:
    calls: list[list[str]] = []

    def fake_run(command, check):
        calls.append(command)
        assert check is True
        return None

    monkeypatch.setattr(subprocess, "run", fake_run)

    write_flash(
        "/tmp/fw.bin",
        config=FlashromConfig(programmer="serprog:dev=/dev/ttyACM0", chip="W25X10"),
        verify=False,
    )

    assert calls == [[
        "flashrom",
        "-p",
        "serprog:dev=/dev/ttyACM0",
        "-c",
        "W25X10",
        "-n",
        "-w",
        "/tmp/fw.bin",
    ]]


def test_missing_flashrom_binary_is_reported(monkeypatch) -> None:
    def fake_run(command, check):
        raise FileNotFoundError(command[0])

    monkeypatch.setattr(subprocess, "run", fake_run)

    with pytest.raises(FlasherError, match="was not found"):
        read_flash("/tmp/backup.bin", config=FlashromConfig(programmer="ch341a_spi"))
