#!/usr/bin/env python3
"""Main entry point for rocprof-compute"""

# Copyright (c) Advanced Micro Devices, Inc.
# SPDX-License-Identifier:  MIT

import re
import signal
import sys
import traceback
import warnings
from pathlib import Path
from typing import Tuple

# Suppress pandas FutureWarning about chained assignment
warnings.filterwarnings("ignore", category=FutureWarning)

_ANALYZE_DEPS_DOC = (
    "Install the analyze dependencies into their own virtual environment: "
    "https://rocm.docs.amd.com/projects/rocprofiler-compute/en/latest/"
    "install/core-install.html#analyze-deps"
)

try:
    from importlib import metadata

    from rocprof_compute_base import RocProfCompute
    from utils.logger import console_error, console_log
except ImportError as e:
    print(f"{e}")
    # In wheel package, softlink is not supported.
    # rocprof-compute will get installed in bin and libexec/rocprofiler-compute.
    # When invoked from bin folder, the extra paths are required to import the
    # dependent scripts

    try:
        current_path = Path(__file__).resolve().parent
        additional_path = current_path / "../libexec/rocprofiler-compute"
        sys.path.append(str(additional_path.resolve()))

        from importlib import metadata

        from rocprof_compute_base import RocProfCompute
        from utils.logger import console_error, console_log
    except ImportError:
        print(
            "\n[ERROR] Could not import rocprofiler-compute modules. "
            "Please check your installation."
        )
        script_path = Path(__file__).resolve().parent
        print(f"Searched: {script_path}, {additional_path.resolve()}")
        traceback.print_exc()
        sys.exit(1)


def check_version(local_ver: str, desired_ver: str, operator: str) -> bool:
    """Compare dotted package versions with the operators used in requirements.txt.

    Comparison is numeric, so 2.10.0 is greater than 2.9.0, and 2.6 equals 2.6.0.
    Text such as rc1, dev0 or a local suffix after '+' is ignored.
    """
    local, desired = _pad_to_same_length(
        _numeric_version(local_ver), _numeric_version(desired_ver)
    )
    ops = {
        "==": local == desired,
        "!=": local != desired,
        ">=": local >= desired,
        "<=": local <= desired,
        ">": local > desired,
        "<": local < desired,
    }
    return ops[operator]


def check_python_version() -> None:
    """Check the baseline Python version required to launch rocprofiler-compute.

    Profile mode runs on Python 3.8+ (standard library only). Analyze mode has a
    higher floor enforced separately in check_analyze_python_version().
    """
    min_python = (3, 8)
    # Check which version of python is being used
    if sys.version_info < min_python:  # noqa: UP036
        console_error(
            f"Python {min_python[0]}.{min_python[1]} or higher "
            "is required for rocprofiler-compute. "
            "The current version is "
            f"{sys.version_info[0]}.{sys.version_info[1]}."
        )


def check_analyze_python_version() -> None:
    """Enforce the analyze-mode Python floor (its dependencies require 3.9+)."""
    min_python = (3, 9)
    if sys.version_info < min_python:
        console_error(
            f"analyze mode requires Python {min_python[0]}.{min_python[1]} "
            "or higher. The current version is "
            f"{sys.version_info[0]}.{sys.version_info[1]}. "
            "Profile mode supports Python 3.8+."
        )


def verify_deps() -> None:
    """Verify that all required packages from requirements.txt are installed
    with correct versions for analyze mode execution.

    NOTE: Only called for analyze mode. Profile mode requires no external
    dependencies (uses stdlib only).
    """
    bindir = str(Path(__file__).resolve().parent)
    deps_locations = ["requirements.txt", "../requirements.txt"]
    python_version = f"{sys.version_info.major}.{sys.version_info.minor}"

    for location in deps_locations:
        check_file = Path(bindir).joinpath(location)
        if check_file.exists():
            dependencies = check_file.read_text(encoding="utf-8").splitlines()

            error = False
            requirement_pattern = re.compile(r"^([^=<>!]*)(.*)$")

            for dependency in dependencies:
                dependency = dependency.strip()
                if not dependency or dependency.startswith("#"):
                    continue

                # Skip requirements whose python_version marker excludes this
                # interpreter. Any other marker is treated as applicable.
                requirement, _, marker = dependency.partition(";")
                marker = marker.strip()
                if marker.startswith("python_version") and not _meets_bounds(
                    python_version, marker[len("python_version") :]
                ):
                    continue
                dependency = requirement.strip()

                package, bounds = requirement_pattern.match(dependency).groups()
                package = package.strip()

                try:
                    local_version = metadata.distribution(package).version
                except metadata.PackageNotFoundError:
                    error = True
                    console_error(
                        f"The '{dependency}' package was not found "
                        "in the current execution environment.",
                        exit=False,
                    )
                    continue

                # Check version requirement
                if bounds and not _meets_bounds(local_version, bounds):
                    console_error(
                        f"the '{dependency}' distribution does not meet "
                        "version requirements to use rocprofiler-compute."
                        f"\n  --> version installed : {local_version}",
                        exit=False,
                    )
                    error = True

            if error:
                console_error(
                    "\nAnalyze mode needs every dependency listed above before "
                    "it can run."
                    f"\n\n{_ANALYZE_DEPS_DOC}"
                )
            return

    searched = [
        str(Path(bindir).joinpath(location).resolve()) for location in deps_locations
    ]
    console_error(
        "Cannot find requirements.txt at "
        f"{', '.join(searched)}"
        ", so the analyze dependencies could not be checked."
        f"\n\n{_ANALYZE_DEPS_DOC}"
    )


def set_signal_handlers() -> None:
    """Set the signal handlers.

    - SIGTERM: exit through SystemExit so finally blocks still run. For example,
      container attach deletes its staging folder in the target's /tmp.
    """
    signal.signal(signal.SIGTERM, lambda signum, _frame: sys.exit(128 + signum))


def main() -> None:
    """Main function for rocprofiler-compute"""

    set_signal_handlers()

    # Baseline Python floor for any mode (profile is 3.8+); analyze adds its own
    check_python_version()

    rocprof_compute = RocProfCompute()
    mode = rocprof_compute.get_mode()

    # major rocprofiler-compute execution modes
    if mode == "profile":
        rocprof_compute.run_profiler()
    elif mode == "analyze":
        # Analyze mode needs a higher Python floor and external dependencies
        check_analyze_python_version()
        verify_deps()
        if rocprof_compute.get_args().debug_verify_deps:
            console_log("All analyze dependencies are installed.")
            sys.exit(0)
        rocprof_compute.run_analysis()
    else:
        console_error("Unsupported execution mode")

    sys.exit(0)


def _meets_bounds(version: str, bounds: str) -> bool:
    """Check a version against comma-separated bounds, such as >=1.26.4,<2.6.

    A bound may quote its version, as python_version markers do.
    """
    for bound in bounds.split(","):
        match = re.match(r"^\s*(==|!=|>=|<=|>|<)\s*[\"']?([0-9.]+)[\"']?\s*$", bound)
        if not match:
            console_error(
                f"Cannot read the version bound '{bound.strip()}' in requirements.txt."
            )
        operator, desired_version = match.groups()
        if not check_version(version, desired_version, operator):
            return False
    return True


def _numeric_version(version: str) -> Tuple[int, ...]:
    """Integer parts of the public dotted version, ignoring a '+' suffix.

    2.13.0+rocm7.15.0a20260728 is (2, 13, 0).
    """
    public = version.split("+", 1)[0]
    return tuple(int(part) for part in public.split(".") if part.isdigit())


def _pad_to_same_length(
    first: Tuple[int, ...], second: Tuple[int, ...]
) -> Tuple[Tuple[int, ...], Tuple[int, ...]]:
    """Pad the shorter version with zeros, so both have the same number of parts."""
    width = max(len(first), len(second))
    return first + (0,) * (width - len(first)), second + (0,) * (width - len(second))


if __name__ == "__main__":
    main()
