import hashlib

import pytest

from mirage.commands.builtin.generic.cmp import cmp_cmd
from mirage.commands.builtin.generic.md5 import md5
from mirage.commands.builtin.generic.sha256sum import sha256sum_generic
from mirage.commands.config import CommandOpts
from mirage.types import FileStat, FileType, PathSpec


def _spec(path: str) -> PathSpec:
    return PathSpec(resource_path=(path).strip("/"),
                    virtual=path,
                    directory=path,
                    resolved=True)


def _make_backend(files: dict[str, bytes]):

    async def read_bytes(path):
        key = path.virtual if isinstance(path, PathSpec) else path
        if key not in files:
            raise FileNotFoundError(key)
        return files[key]

    async def read_stream(path):
        key = path.virtual if isinstance(path, PathSpec) else path
        if key not in files:
            raise FileNotFoundError(key)
        yield files[key]

    return read_bytes, read_stream


def _make_stat(files: dict[str, bytes]):

    async def stat(path):
        key = path.virtual if isinstance(path, PathSpec) else path
        if key not in files:
            raise FileNotFoundError(key)
        return FileStat(name=key, size=len(files[key]), type=FileType.TEXT)

    return stat


async def _drain(stdout) -> bytes:
    if stdout is None:
        return b""
    if isinstance(stdout, bytes):
        return stdout
    return b"".join([c async for c in stdout])


@pytest.mark.asyncio
async def test_md5_single_file():
    rb, _ = _make_backend({"/a.txt": b"hello\n"})
    output, _ = await md5([_spec("/a.txt")], read_bytes=rb)
    decoded = output.decode()
    expected = hashlib.md5(b"hello\n").hexdigest()
    assert expected in decoded
    assert "/a.txt" in decoded


@pytest.mark.asyncio
async def test_md5_multi_file_emits_one_line_each():
    rb, _ = _make_backend({"/a.txt": b"a", "/b.txt": b"b"})
    output, _ = await md5([_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb)
    lines = output.decode().splitlines()
    assert len(lines) == 2


@pytest.mark.asyncio
async def test_md5_no_paths_raises():
    rb, _ = _make_backend({})
    with pytest.raises(ValueError, match="missing operand"):
        await md5([], read_bytes=rb)


@pytest.mark.asyncio
async def test_sha256sum_stdin():
    files: dict[str, bytes] = {}
    _, rs = _make_backend(files)
    output, _ = await sha256sum_generic([], [], CommandOpts(stdin=b"hello\n"),
                                        _make_stat(files), rs)
    decoded = (await _drain(output)).decode()
    expected = hashlib.sha256(b"hello\n").hexdigest()
    assert expected in decoded
    assert decoded.strip().endswith("-")


@pytest.mark.asyncio
async def test_sha256sum_multi_file():
    files = {"/a.txt": b"foo", "/b.txt": b"bar"}
    _, rs = _make_backend(files)
    output, _ = await sha256sum_generic(
        [_spec("/a.txt"), _spec("/b.txt")], [], CommandOpts(),
        _make_stat(files), rs)
    decoded = (await _drain(output)).decode().splitlines()
    assert len(decoded) == 2
    assert hashlib.sha256(b"foo").hexdigest() in decoded[0]
    assert hashlib.sha256(b"bar").hexdigest() in decoded[1]


@pytest.mark.asyncio
async def test_sha256sum_missing_operand_reports_and_continues():
    files = {"/a.txt": b"foo"}
    _, rs = _make_backend(files)
    output, io = await sha256sum_generic(
        [_spec("/a.txt"), _spec("/nope")], [], CommandOpts(),
        _make_stat(files), rs)
    decoded = (await _drain(output)).decode()
    assert hashlib.sha256(b"foo").hexdigest() in decoded
    assert io.exit_code == 1
    assert b"sha256sum: /nope: No such file or directory\n" in io.stderr


@pytest.mark.asyncio
async def test_sha256sum_check_passing():
    payload = b"hello"
    digest = hashlib.sha256(payload).hexdigest()
    manifest = f"{digest}  /file.txt\n".encode()
    files = {
        "/manifest.sha256": manifest,
        "/file.txt": payload,
    }
    _, rs = _make_backend(files)
    output, io = await sha256sum_generic([_spec("/manifest.sha256")], [],
                                         CommandOpts(flags={"check": True}),
                                         _make_stat(files), rs)
    assert b"/file.txt: OK" in await _drain(output)
    assert io.exit_code == 0


@pytest.mark.asyncio
async def test_sha256sum_check_failing():
    manifest = b"deadbeef  /file.txt\n"
    files = {
        "/manifest.sha256": manifest,
        "/file.txt": b"actual content",
    }
    _, rs = _make_backend(files)
    output, io = await sha256sum_generic([_spec("/manifest.sha256")], [],
                                         CommandOpts(flags={"check": True}),
                                         _make_stat(files), rs)
    assert b"/file.txt: FAILED" in await _drain(output)
    assert io.exit_code == 1


@pytest.mark.asyncio
async def test_cmp_identical_returns_nothing():
    rb, _ = _make_backend({"/a.txt": b"same", "/b.txt": b"same"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb)
    assert output is None
    assert io.exit_code == 0


@pytest.mark.asyncio
async def test_cmp_differing_reports_first_byte():
    rb, _ = _make_backend({"/a.txt": b"hello", "/b.txt": b"hallo"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb)
    assert output == b"/a.txt /b.txt differ: char 2, line 1\n"
    assert io.exit_code == 1


@pytest.mark.asyncio
async def test_cmp_silent_mode():
    rb, _ = _make_backend({"/a.txt": b"x", "/b.txt": b"y"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb, silent=True)
    assert output is None
    assert io.exit_code == 1


@pytest.mark.asyncio
async def test_cmp_verbose_lists_all_diffs():
    rb, _ = _make_backend({"/a.txt": b"abc", "/b.txt": b"axc"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb, verbose=True)
    assert b"2 142 170" in output
    assert io.exit_code == 1


@pytest.mark.asyncio
async def test_cmp_skip_offset():
    rb, _ = _make_backend({"/a.txt": b"xxhello", "/b.txt": b"yyhello"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb, skip=(2, 2))
    assert output is None
    assert io.exit_code == 0


@pytest.mark.asyncio
async def test_cmp_requires_two_paths():
    rb, _ = _make_backend({"/a.txt": b"x"})
    with pytest.raises(ValueError, match="two paths"):
        await cmp_cmd([_spec("/a.txt")], read_bytes=rb)


@pytest.mark.asyncio
async def test_cmp_eof_on_shorter():
    rb, _ = _make_backend({"/a.txt": b"abc", "/b.txt": b"abcdef"})
    output, io = await cmp_cmd(
        [_spec("/a.txt"), _spec("/b.txt")], read_bytes=rb)
    # GNU writes this to stderr, not stdout, and names the byte it
    # stopped at plus the line that byte sits in.
    assert output is None
    assert io.stderr == b"cmp: EOF on /a.txt after byte 3, in line 1\n"
    assert io.exit_code == 1
