"""Sequential SARIF file numbering with race condition handling."""

import os
import re
from pathlib import Path

from tools.generate_report.models import AuditLens

MAX_RETRY_ATTEMPTS = 10


def get_highest_sarif_number(reports_dir: Path, lens: AuditLens) -> int:
    """Scan reports directory to find the highest existing SARIF number for a lens.

    Args:
        reports_dir: Path to the reports directory
        lens: The audit lens to scan for

    Returns:
        Highest existing SARIF number, or 0 if none exist
    """
    if not reports_dir.exists():
        return 0

    pattern = re.compile(rf"^SARIF_{lens.value}_(\d+)\.sarif\.json$")
    highest = 0

    for file_path in reports_dir.iterdir():
        if file_path.is_file():
            match = pattern.match(file_path.name)
            if match:
                num = int(match.group(1))
                highest = max(highest, num)

    return highest


def allocate_sarif_number(reports_dir: Path, lens: AuditLens) -> tuple[int, Path]:
    """Allocate the next available SARIF file number atomically.

    Args:
        reports_dir: Path to the reports directory
        lens: The audit lens for the SARIF file

    Returns:
        Tuple of (sarif_number, sarif_path)

    Raises:
        RuntimeError: If all retry attempts are exhausted
    """
    base_num = get_highest_sarif_number(reports_dir, lens)

    for attempt in range(MAX_RETRY_ATTEMPTS):
        candidate_num = base_num + 1 + attempt
        candidate_path = reports_dir / f"SARIF_{lens.value}_{candidate_num}.sarif.json"

        try:
            fd = os.open(candidate_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
            os.close(fd)
            return candidate_num, candidate_path

        except FileExistsError:
            continue

    raise RuntimeError(
        f"Failed to allocate SARIF file number after {MAX_RETRY_ATTEMPTS} attempts. "
        f"Consider cleaning up old SARIF files in {reports_dir}."
    )
