import re

from actions_logging.app_logging import logger
from common.common import raise_with_context
from github.env import exit_on_error_and_write_summary, get_required_env_var


def regex_match(string: str, pattern: str, raise_error_on_mismatch: bool = False) -> bool:
    """
    Check if the entire string matches the given regex pattern.
    Also validates if the pattern itself is a valid regex.

    :param string: The input string to validate.
    :param pattern: The regex pattern to match against.
    :param raise_error_on_mismatch: If True, raises an error if the mismatch instead of returning False.
    :return: True if the string matches the pattern, False otherwise.
    """

    try:
        logger.debug(f"Validation regex pattern {pattern}")
        compiled_pattern = re.compile(pattern)  # Validate regex pattern
    except re.error as e:
        raise_with_context(e, ValueError, "Invalid regex pattern")

    try:
        logger.debug(f"Checking if string {string} matches regex pattern {pattern}")
        match = compiled_pattern.fullmatch(string)

        if raise_error_on_mismatch and not match:
            logger.debug(f"String {string} does not match regex pattern {pattern}. Raising error.")
            raise_with_context(None, ValueError, f"String '{string}' does not match the pattern '{pattern}'")

        logger.info(f"Validation of string {string} against regex pattern {pattern} return {match}")
        return bool(match)
    except RuntimeError as e:
        raise_with_context(e, RuntimeError, f"Error validating string '{string}' against pattern '{pattern}'")


def main():
    # When calling this script directly (not importing it in another Python script),
    # the string and regex pattern must exist in environment variables.
    # Then, if there's no match an error is raised and caught by the main script.
    string_to_validate = get_required_env_var("STRING_TO_VALIDATE")
    regex_pattern = get_required_env_var("REGEX_PATTERN")
    try:
        regex_match(string_to_validate, regex_pattern, True)
    except Exception as e:
        exit_on_error_and_write_summary(f"Validation failed: {e}")


if __name__ == "__main__":
    main()
