import os
import hashlib
import pytest
from pathlib import Path
from utils.file_handler import file_handler, FileHandler


def test_calculate_sha256(tmp_path):
    test_file = tmp_path / "test.txt"
    content = b"Hello, BMAD!"
    test_file.write_bytes(content)

    expected_hash = hashlib.sha256(content).hexdigest()
    actual_hash = file_handler.calculate_sha256(test_file)

    assert actual_hash == expected_hash


def test_calculate_sha256_nonexistent_file(tmp_path):
    nonexistent = tmp_path / "does_not_exist.txt"
    result = file_handler.calculate_sha256(nonexistent)
    assert result is None


def test_calculate_sha256_large_file(tmp_path):
    test_file = tmp_path / "large.bin"
    content = os.urandom(1024 * 1024)
    test_file.write_bytes(content)

    expected_hash = hashlib.sha256(content).hexdigest()
    actual_hash = file_handler.calculate_sha256(test_file)

    assert actual_hash == expected_hash


def test_get_file_info_with_hash(tmp_path):
    test_file = tmp_path / "test.txt"
    content = b"Metadata test"
    test_file.write_bytes(content)

    expected_hash = hashlib.sha256(content).hexdigest()
    info = file_handler.get_file_info(test_file)

    assert "sha256" in info
    assert info["sha256"] == expected_hash
    assert info["filename"] == "test.txt"
    assert info["size_bytes"] == len(content)


def test_get_file_info_nonexistent(tmp_path):
    nonexistent = tmp_path / "does_not_exist.txt"
    info = file_handler.get_file_info(nonexistent)
    assert info == {}


def test_cleanup_file_success(tmp_path, caplog):
    test_file = tmp_path / "to_delete.txt"
    test_file.write_bytes(b"delete me")

    assert test_file.exists()
    file_handler.cleanup_file(test_file)
    assert not test_file.exists()


def test_cleanup_file_nonexistent(tmp_path, caplog):
    nonexistent = tmp_path / "does_not_exist.txt"
    file_handler.cleanup_file(nonexistent)
