from __future__ import annotations

import uuid

import isort


def safe_isort(code: str, **kwargs) -> str:  # noqa: ANN003
    """Wrap isort.code to returns the original code if isort fails.

    Args:
        code (str): The Python source code to sort imports for.
        **kwargs: Any additional keyword arguments accepted by isort.code.

    Returns:
        str: The sorted code, or the original code if an exception is raised.

    """
    try:
        return isort.code(code, **kwargs)
    except Exception:  # noqa: BLE001
        return code


def parse_python_version(version: str | None) -> tuple[int, int, int]:
    if not version:
        raise ValueError("Python version is required")
    assert len(version) < 30, "Invalid version format"
    split_version = version.split(".")
    if len(split_version) != 3:
        raise ValueError("Invalid version format")
    major, minor, patch = int(split_version[0]), int(split_version[1]), int(split_version[2])
    assert major == 3, "Only Python 3 is supported"
    assert minor >= 9, "Only Python 3.9 and above is supported"
    assert minor <= 14, "Unsupported Python version"
    assert patch >= 0, "Only Python 3.9 and above is supported"
    assert patch < 100, "Invalid version format"

    return (major, minor, patch)


def validate_trace_id(trace_id: str) -> bool:
    try:
        uuid_obj = uuid.UUID(trace_id, version=4)
        if str(uuid_obj) != trace_id:
            raise ValueError
        return True

    except ValueError:
        if trace_id[-4:] in ["EXP0", "EXP1"]:
            temp_trace_id = trace_id[:-4] + "0000"
            return validate_trace_id(temp_trace_id)
        return False


CODEFLASH_EMPLOYEE_GITHUB_IDS = {
    "github|1271289",
    "github|10488227",
    "github|64513301",
    "github|106575910",
    "github|206515457",
    "github|4725571",
    "github|235426847",
}


def is_codeflash_employee(user_id: str) -> bool:
    return user_id in CODEFLASH_EMPLOYEE_GITHUB_IDS


def should_hack_for_demo(source_code: str) -> bool:
    return bool("def find_common_tags(articles" in source_code) or bool("def weighted_sum(series" in source_code)
