"""Benchmark tests for file operation throughput."""

import tempfile
import time
from pathlib import Path

import pytest

from cleave.core.file_utils import atomic_write_text


@pytest.mark.benchmark
def test_file_write_small():
    """Benchmark writing small files."""
    with tempfile.TemporaryDirectory() as tmpdir:
        content = "x" * 1000  # 1KB

        start = time.perf_counter()

        for i in range(100):
            path = Path(tmpdir) / f"file_{i}.txt"
            atomic_write_text(path, content)

        elapsed = time.perf_counter() - start

        print(f"\n100 small file writes (1KB each): {elapsed:.6f}s")
        assert elapsed < 5.0  # Should complete within 5 seconds


@pytest.mark.benchmark
def test_file_write_medium():
    """Benchmark writing medium files."""
    with tempfile.TemporaryDirectory() as tmpdir:
        content = "x" * 100_000  # 100KB

        start = time.perf_counter()

        for i in range(50):
            path = Path(tmpdir) / f"file_{i}.txt"
            atomic_write_text(path, content)

        elapsed = time.perf_counter() - start

        print(f"\n50 medium file writes (100KB each): {elapsed:.6f}s")
        assert elapsed < 5.0


@pytest.mark.benchmark
def test_file_write_large():
    """Benchmark writing large files."""
    with tempfile.TemporaryDirectory() as tmpdir:
        content = "x" * 1_000_000  # 1MB

        start = time.perf_counter()

        for i in range(10):
            path = Path(tmpdir) / f"file_{i}.txt"
            atomic_write_text(path, content)

        elapsed = time.perf_counter() - start

        print(f"\n10 large file writes (1MB each): {elapsed:.6f}s")
        assert elapsed < 5.0


@pytest.mark.benchmark
def test_file_read_throughput():
    """Benchmark file read throughput."""
    with tempfile.TemporaryDirectory() as tmpdir:
        # Setup: create files
        content = "x" * 10_000  # 10KB
        files = []

        for i in range(100):
            path = Path(tmpdir) / f"file_{i}.txt"
            atomic_write_text(path, content)
            files.append(path)

        # Benchmark: read all files
        start = time.perf_counter()

        for path in files:
            data = path.read_text()
            assert len(data) == 10_000

        elapsed = time.perf_counter() - start

        print(f"\n100 file reads (10KB each): {elapsed:.6f}s")
        assert elapsed < 2.0
