"""
Allure Report Summarizer

This module provides comprehensive functionality to analyze and summarize Allure test reports.
It processes Allure HTML report files to extract detailed test execution statistics, timing
information, and test status data, providing both high-level summaries and detailed analysis.

Key Features:
- Extracts test execution timing information (start time, stop time, duration)
- Calculates comprehensive test statistics (total, passed, failed, broken, skipped, unknown)
- Computes pass rate percentages with precise formatting
- Identifies and tracks unique test cases by their status
- Generates formatted summary reports for both console and file output
- Handles multiple file encodings (UTF-8, Latin1, CP1252, ISO-8859-1) for robust reading
- Exports test results to JSON files for further analysis and integration
- Provides both command-line interface and programmatic API access

The module is specifically designed to work with Allure HTML reports and offers both
summary statistics and granular test case information for comprehensive test analysis.

Core Functions:
    - summarize_html_report(): Main function for generating complete report summaries
    - get_unique_test_count(): Detailed test case analysis with status breakdown
    - save_summary_to_file(): Export summary data to human-readable text files
    - get_report_path(): Utility for locating report files in directories

Example Usage:
    # Basic report summarization
    >>> report_path = "path/to/allure-report/index.html"
    >>> summary = summarize_html_report(report_path)
    >>> print(summary)
    {
        'start_time': '2024-03-01 10:00:00',
        'stop_time': '2024-03-01 11:00:00',
        'duration': '1 hours 0 minutes 0 seconds',
        'total': 100,
        'passed': 90,
        'failed': 10,
        'broken': 0,
        'skipped': 0,
        'unknown': 0,
        'pass_rate': '90.00%'
    }

    # Save formatted summary to file
    >>> save_summary_to_file(summary, "test_summary.txt")

    # Get detailed test statistics
    >>> test_stats = get_unique_test_count(report_path)
    >>> print(f"Failed tests: {len(test_stats['failed'])}")
    Failed tests: 10

    # Command line usage
    $ export ALLURE_REPORT_PATH="/path/to/reports"
    $ python report_summarize.py

Requirements:
    - Python 3.6+
    - Allure HTML report files

Environment Variables:
    - ALLURE_REPORT_PATH: Directory containing Allure HTML reports
    - JSON_FILE_PATH: Directory for JSON output files (default: c:\\reports\\json_files)

Output Files:
    - failed_testscripts.json: Sorted list of failed test case IDs
    - passed_testscripts.json: Sorted list of passed test case IDs
"""

import json
import os
import re
from datetime import datetime
from typing import Any, Dict, List, Optional

# Constants
DEFAULT_JSON_PATH = "c:\\reports\\json_files"
FAILED_TESTS_JSON = "failed_testscripts.json"
PASSED_TESTS_JSON = "passed_testscripts.json"
SUMMARY_WIDGET_KEY = "widgets/summary.json"
TEST_CASES_PATTERN = r'"data[\\/]+test-cases[\\/]+(?P<uid>[^"]+?)\.json"\s*:\s*"(?P<json>((?:[^"\\]|\\.)*))"'
TEST_ID_PATTERN = r"(T\d+)"
ENCODINGS = ["utf-8", "latin1", "cp1252", "iso-8859-1"]
DATE_FORMAT = "%Y-%m-%d %H:%M:%S"

# Configure JSON output directory from environment variable or use default
json_file_path = os.environ.get("JSON_FILE_PATH", DEFAULT_JSON_PATH)
if json_file_path == DEFAULT_JSON_PATH:  # Check for unset environment variable
    print("JSON_FILE_PATH is not set. Defaulting to c:\\reports\\json_files")
else:
    print(f"JSON file path: {json_file_path}")

# Ensure the JSON output directory exists
if not os.path.exists(json_file_path):
    os.makedirs(json_file_path, exist_ok=True)
    print(f"Created JSON output directory: {json_file_path}")

def get_filename(directory: str) -> str:
    """
    Gets the first HTML file found in the specified directory.

    This function searches for HTML files in the given directory and returns the name
    of the first one found. It's typically used to locate Allure report files.

    Args:
        directory (str): Path to the directory containing HTML report files

    Returns:
        str: Name of the first HTML file found, or empty string if no HTML files found

    Raises:
        Exception: If there's an error accessing the directory

    Example:
        >>> get_filename("reports/")
        'report_20240301.html'
    """
    try:
        # Find html files in the directory
        files = os.listdir(directory)
        html_files = [file for file in files if file.endswith(".html")]
        return html_files[0] if html_files else ""
    except Exception as e:
        print(f"Error in getting filename: {e}")
        return ""


def summarize_html_report(report_path: str) -> Dict[str, Any]:
    """
    Summarizes an Allure test report by extracting test execution statistics and timing information.

    This function processes an Allure HTML report file to extract comprehensive test execution
    data including timing information, test counts by status, and calculates the pass rate.
    It handles JSON data embedded within the HTML report and performs necessary data cleaning
    and validation.

    Args:
        report_path (str): Path to the Allure HTML report file

    Returns:
        Dict[str, Any]: A dictionary containing:
            - start_time: Test execution start time (YYYY-MM-DD HH:MM:SS)
            - stop_time: Test execution stop time (YYYY-MM-DD HH:MM:SS)
            - duration: Total duration in hours, minutes, and seconds
            - total: Total number of tests
            - passed: Number of passed tests
            - failed: Number of failed tests
            - broken: Number of broken tests
            - skipped: Number of skipped tests
            - unknown: Number of tests with unknown status
            - pass_rate: Percentage of passed tests (XX.XX%)

    Raises:
        FileNotFoundError: If the report file doesn't exist
        ValueError: If the report format is invalid or required data is missing
        json.JSONDecodeError: If the report contains invalid JSON data
        KeyError: If required data fields are missing from the report

    Example:
        >>> summary = summarize_html_report("report.html")
        >>> print(summary["pass_rate"])
        '90.00%'
    """
    print(f"Reading summary from {report_path}")
    # Initialize default summary with zero values
    summary = {
        "start_time": "",
        "stop_time": "",
        "duration": "0 hours 0 minutes 0 seconds",
        "total": 0,
        "passed": 0,
        "failed": 0,
        "broken": 0,
        "skipped": 0,
        "unknown": 0,
        "pass_rate": "0.00%",
    }

    try:
        # Read the report file
        if not os.path.exists(report_path):
            raise FileNotFoundError(f"Report file not found: {report_path}")

        with open(report_path, "r", encoding="utf-8", errors="ignore") as file:
            content = file.read()

        # Locate and extract embedded JSON summary data from HTML
        index = content.find(SUMMARY_WIDGET_KEY)
        if index == -1:
            raise ValueError("Could not find summary data in the report file")

        # Extract the JSON string from embedded HTML content
        # The JSON is embedded as: "widgets/summary.json": "{...}"});
        trim_at_start = f'{SUMMARY_WIDGET_KEY}": "'
        content = content.replace(trim_at_start, "")
        content = content[index:]

        # Find the end of the JSON object (marked by "};")
        index = content.find("};")
        if index == -1:
            raise ValueError("Invalid report format: missing closing bracket")

        # Extract JSON content and clean up formatting
        content = content[0 : index - 4]  # Remove trailing ", };
        content = content.replace("\\", "")  # Unescape backslashes for valid JSON

        # Parse the JSON content
        try:
            content = json.loads(content)
        except json.JSONDecodeError as e:
            raise ValueError(f"Invalid JSON data in report: {str(e)}")

        # Extract and validate required data
        if "statistic" not in content or "time" not in content:
            raise KeyError("Missing required data fields in report")

        content["statistic"]
        time_data = content["time"]

        # Extract and format test execution timing information
        try:
            start_time = time_data["start"]      # Epoch timestamp in milliseconds
            stop_time = time_data["stop"]        # Epoch timestamp in milliseconds
            duration_ms = time_data["duration"]  # Duration in milliseconds

            # Convert milliseconds to seconds for datetime conversion
            duration = int(duration_ms / 1000)

            # Convert epoch timestamps to human-readable date/time format
            start_time_human = datetime.fromtimestamp(start_time / 1000).strftime(DATE_FORMAT)
            stop_time_human = datetime.fromtimestamp(stop_time / 1000).strftime(DATE_FORMAT)

            # Break down total duration into hours, minutes, and seconds
            duration_hours = int(duration / 3600)
            duration_minutes = int((duration - duration_hours * 3600) / 60)
            duration_seconds = int(duration - duration_hours * 3600 - duration_minutes * 60)

            # Format and store timing information
            summary["start_time"] = start_time_human
            summary["stop_time"] = stop_time_human
            summary["duration"] = f"{duration_hours} hours {duration_minutes} minutes {duration_seconds} seconds"
        except (KeyError, ValueError, TypeError) as e:
            print(f"Warning: Error processing timing data: {str(e)}")
            print("Timing information will show default values")

        # Process test statistics
        try:
            test_stats = get_unique_test_count(report_path)
            summary["total"] = len(test_stats["total"])
            summary["passed"] = len(test_stats["passed"])
            summary["failed"] = len(test_stats["failed"])
            summary["broken"] = len(test_stats["broken"])
            summary["skipped"] = len(test_stats["skipped"])
            summary["unknown"] = len(test_stats["unknown"])

            # Calculate pass rate
            if summary["total"] > 0:
                summary["pass_rate"] = f"{summary['passed'] / summary['total'] * 100:.2f}%"
            else:
                summary["pass_rate"] = "0.00%"
        except KeyError as e:
            print(f"Warning: Missing statistic field: {str(e)}")
        except ZeroDivisionError:
            print("Warning: Total test count is zero")

    except Exception as e:
        print(f"Error processing report: {str(e)}")

    return summary


def save_summary_to_file(summary: Dict[str, Any], file_path: str):
    """
    Saves the summary data to a text file in a human-readable format.

    This function takes a summary dictionary and writes its contents to a text file,
    formatting the keys to be more readable (e.g., "start_time" becomes "Start Time").
    The output is both printed to console and written to the specified file.

    Args:
        summary (Dict[str, Any]): The summary data to save
        file_path (str): The path where the summary will be saved

    Raises:
        IOError: If the file cannot be written

    Example:
        >>> summary = summarize_html_report("report.html")
        >>> save_summary_to_file(summary, "report_summary.txt")
        Start Time: 2024-03-01 10:00:00
        Stop Time: 2024-03-01 11:00:00
        Duration: 1 hours 0 minutes 0 seconds
        ...
    """
    try:
        with open(file_path, "w", encoding="utf-8") as file:
            for key, value in summary.items():
                # Format the key for display (replace underscores with spaces and capitalize)
                display_key = key.replace("_", " ").title()
                print(f"{display_key}: {value}")
                file.write(f"{display_key}: {value}\n")
        print(f"\nSummary saved to: {file_path}")
    except IOError as e:
        print(f"Error saving summary file: {str(e)}")


def get_report_path(attachment_path: str) -> str:
    """
    Gets the path to the latest report file in the specified directory.

    This function combines the directory path with the first HTML file found
    to create a complete file path for report processing.

    Args:
        attachment_path (str): The path to the directory containing report files

    Returns:
        str: The complete path to the report file

    Raises:
        FileNotFoundError: If the report directory doesn't exist
        ValueError: If no report files are found in the directory

    Example:
        >>> report_path = get_report_path("reports/")
        'reports/report_20240301.html'
    """
    try:
        # Get the latest report filename
        filename = get_filename(attachment_path)
        if not filename:
            print("No report file found")
            exit(1)
        # Generate the full report path
        report_path = os.path.join(attachment_path, filename)
        return report_path
    except Exception as e:
        print(f"Error in getting report path: {str(e)}")


def get_summary_message(summary: Dict[str, Any]) -> str:
    """
    Converts a summary dictionary into a formatted string message.

    This function transforms the summary dictionary into a human-readable string
    format, with each key-value pair on a new line. Keys are formatted to be
    more readable (e.g., "start_time" becomes "Start Time").

    Args:
        summary (Dict[str, Any]): The summary data to convert

    Returns:
        str: A formatted string message containing the summary data

    Example:
        >>> summary = summarize_html_report("report.html")
        >>> message = get_summary_message(summary)
        >>> print(message)
        Start Time: 2024-03-01 10:00:00
        Stop Time: 2024-03-01 11:00:00
        Duration: 1 hours 0 minutes 0 seconds
        Total tests: 100
        Passed: 90
        Failed: 10
        Broken: 0
        Skipped: 0
        Unknown: 0
        Pass rate: 90.00%
        ...
    """
    summary_message = ""
    try:
        for k, v in summary.items():
            # Format the key for display (replace underscores with spaces and capitalize)
            key = k.replace("_", " ").title()
            summary_message += f"{key}: {v}\n"
    except Exception as e:
        print(f"Error in getting summary message: {str(e)}")
    return summary_message


def get_file_size_in_mb(file_path: str) -> str:
    """
    Calculate and format the size of a file in megabytes.

    This function determines the size of a specified file in megabytes,
    formats the result with 2 decimal places, and appends the 'MB' suffix.

    Args:
        file_path (str): Absolute or relative path to the file

    Returns:
        str: The file size formatted as a string with 'MB' suffix (e.g., "1.23 MB").
             Returns "0 MB" if the file cannot be accessed or an error occurs.

    Raises:
        None: All exceptions are caught internally and return "0 MB"

    Example:
        >>> size = get_file_size_in_mb("allure-report/index.html")
        >>> print(size)
        '2.45 MB'

        >>> size = get_file_size_in_mb("nonexistent.html")
        >>> print(size)
        '0 MB'
    """
    try:
        file_size = os.path.getsize(file_path)
        return f"{file_size / (1024 * 1024):.2f} MB"
    except Exception as e:
        print(f"Error in getting file size: {str(e)}")
        return "0 MB"


# Get source code from html file.
def read_html_file(html_file: str) -> Optional[str]:
    """
    Reads an HTML file using multiple encodings to handle various file formats.

    This function attempts to read the HTML file using different character encodings
    (utf-8, latin1, cp1252, iso-8859-1) to handle various file formats and ensure
    successful reading of the report file.

    Args:
        html_file (str): Path to the HTML file to read

    Returns:
        Optional[str]: The file contents as a string, or None if reading fails

    Example:
        >>> content = read_html_file("report.html")
        >>> if content:
        ...     print("File read successfully")
    """
    encodings = ENCODINGS

    for encoding in encodings:
        try:
            with open(html_file, "r", encoding=encoding) as file:
                return file.read()
        except UnicodeDecodeError:
            continue
        except Exception as e:
            print(f"Error reading file with {encoding} encoding: {e}")
            continue

    print("Failed to read file with any of the attempted encodings")
    return None


def extract_test_data(html_content: str) -> Optional[Dict]:
    """
    Extracts test data from the HTML content by parsing embedded JSON.

    This function locates and extracts the test data JSON from the HTML content,
    handling escaped characters and JSON parsing. It specifically looks for the
    'data/packages.json' section in the HTML file.

    Args:
        html_content (str): The HTML content to parse

    Returns:
        Optional[Dict]: The parsed test data as a dictionary, or None if extraction fails

    Raises:
        ValueError: If the JSON data cannot be found or is invalid

    Example:
        >>> content = read_html_file("report.html")
        >>> test_data = extract_test_data(content)
        >>> if test_data:
        ...     print(f"Found {len(test_data['children'])} test items")
    """
    try:
        key = '"data/packages.json":'
        start_index = html_content.find(key)
        if start_index == -1:
            raise ValueError("'data/packages.json' not found in source.")

        json_start = start_index + len(key)
        substring = html_content[json_start:].lstrip()

        if not substring.startswith('"'):
            raise ValueError("JSON string not properly formatted.")

        end_quote_index = None
        escape = False
        for i in range(1, len(substring)):
            if substring[i] == '"' and not escape:
                end_quote_index = i
                break
            elif substring[i] == "\\" and not escape:
                escape = True
            else:
                escape = False

        if end_quote_index is None:
            raise ValueError("End of JSON string not found.")

        json_escaped = substring[1:end_quote_index]
        json_unescaped = json.loads(f'"{json_escaped}"')
        return json.loads(json_unescaped)
    except Exception as e:
        print(f"Error in extract_test_data: {e}")
        return None


def extract_test_cases_by_uid(html_content: str) -> Dict[str, dict]:
    """
    Extract test case data from Allure HTML reports using unique identifiers.

    This function parses Allure HTML content to extract individual test case data
    embedded as JSON strings. Each test case is identified by a unique UID (Universal
    Identifier) and contains detailed information about test execution, status, and metadata.

    The function uses regex pattern matching to locate embedded JSON data for test cases,
    handling escaped characters and unicode encoding properly.

    Args:
        html_content (str): The complete HTML content of an Allure report as a string.
                           This should contain embedded JSON data for individual test cases.

    Returns:
        Dict[str, dict]: A dictionary mapping test case UIDs to their parsed data.
                        Each value is a dictionary containing test case information such as:
                        - name: Test case name
                        - status: Test execution status
                        - testStage: Test execution stages and steps
                        - parameters: Test parameters (if any)
                        - And other Allure-specific metadata

    Raises:
        None: Exceptions during JSON parsing are caught and logged, but don't interrupt
              processing of other test cases.

    Example:
        >>> html_content = read_html_file("allure-report/index.html")
        >>> test_cases = extract_test_cases_by_uid(html_content)
        >>> print(f"Found {len(test_cases)} test cases")
        Found 150 test cases

        >>> first_uid = list(test_cases.keys())[0]
        >>> print(test_cases[first_uid]['name'])
        'Test user login functionality'
    """
    pattern = TEST_CASES_PATTERN
    matches = re.finditer(pattern, html_content)

    uid_to_testcase: Dict[str, dict] = {}

    for i, match in enumerate(matches):
        uid = match.group("uid")
        escaped_json = match.group("json")

        try:
            unescaped = bytes(escaped_json, "utf-8").decode("unicode_escape")
            data = json.loads(unescaped)
            uid_to_testcase[uid] = data
        except Exception as e:
            print(f"[{i}] Error parsing test case for UID {uid}: {e}")

    return uid_to_testcase


def get_test_ids_by_status(test_items: List[Dict], status: str) -> List[str]:
    """
    Extract and return sorted test case IDs for a given status.

    This function filters test items by status and extracts their test case IDs
    (e.g., "T123") from their names. The IDs are returned in sorted order.

    Args:
        test_items (List[Dict]): List of test item dictionaries
        status (str): The status to filter by (e.g., "passed", "failed")

    Returns:
        List[str]: Sorted list of test case IDs for the given status

    Example:
        >>> test_items = [{"name": "Test T123", "status": "passed"}]
        >>> ids = get_test_ids_by_status(test_items, "passed")
        >>> print(ids)
        ['T123']
    """
    test_ids = []

    for item in test_items:
        test_name = item.get("name", "")
        top_status = item.get("status", "").lower()
        steps = item.get("testStage", {}).get("steps", [])
        step_failed = any(step.get("status", "").lower() == "failed" for step in steps)

        # Determine corrected status (failed takes precedence if any step failed)
        corrected_status = "failed" if step_failed else top_status

        if corrected_status == status.lower():
            match = re.search(TEST_ID_PATTERN, test_name)
            test_ids.append(match.group(1) if match else test_name)

    return sorted(test_ids)


def get_unique_test_count(html_file_path: str) -> Dict[str, List[str]]:
    """
    Analyze test results and return unique test case IDs categorized by status.

    This function performs comprehensive analysis of Allure HTML reports to extract
    unique test case identifiers grouped by their execution status. It handles complex
    status determination including step-level failure detection and ensures accurate
    categorization of test results.

    The function also automatically exports failed and passed test IDs to JSON files
    for integration with other tools and further analysis.

    Args:
        html_file_path (str): Absolute or relative path to the Allure HTML report file

    Returns:
        Dict[str, List[str]]: Dictionary containing sorted lists of unique test case IDs:
            - "total": List of all unique test case IDs found in the report
            - "passed": List of test case IDs that passed execution
            - "failed": List of test case IDs that failed (including step-level failures)
            - "broken": List of test case IDs with broken status
            - "skipped": List of test case IDs that were skipped
            - "unknown": List of test case IDs with unknown status

    Raises:
        None: File reading errors return a failure message string instead of raising exceptions

    Side Effects:
        - Creates/updates "failed_testscripts.json" with sorted failed test IDs
        - Creates/updates "passed_testscripts.json" with sorted passed test IDs
        - Files are saved to the directory specified by JSON_FILE_PATH environment variable

    Example:
        >>> stats = get_unique_test_count("allure-report/index.html")
        >>> print(f"Total unique tests: {len(stats['total'])}")
        Total unique tests: 100

        >>> print(f"Failed tests: {stats['failed'][:3]}")
        Failed tests: ['T001', 'T015', 'T042']

        # JSON files are automatically created:
        # failed_testscripts.json and passed_testscripts.json
    """
    try:
        test_stats: Dict[str, List[str]] = {}

        # Read and preprocess the HTML content
        html_content = read_html_file(html_file_path)
        if not html_content:
            print("Failed to read HTML file - check file path and encoding")
            return {"total": [], "passed": [], "failed": [], "broken": [], "skipped": [], "unknown": []}

        # Clean HTML content to handle escaped quotes in file paths
        html_content = html_content.replace('File "', 'File ').replace('py "', 'py ')

        # Extract individual test case data from embedded JSON
        test_data = extract_test_cases_by_uid(html_content)
        test_items = list(test_data.values())

        # Extract all unique test case IDs from test items
        all_tests = []
        for test in test_items:
            name = test.get("name", "")
            # Extract test ID using regex pattern T followed by digits
            match = re.search(TEST_ID_PATTERN, name)
            test_id = match.group(1) if match else name
            all_tests.append(test_id)
        # Remove duplicates while preserving order
        all_tests = list(dict.fromkeys(all_tests))

        # Categorize test case IDs by their execution status
        passed_ids = get_test_ids_by_status(test_items, "passed")
        failed_ids = get_test_ids_by_status(test_items, "failed")
        broken_ids = get_test_ids_by_status(test_items, "broken")
        skipped_ids = get_test_ids_by_status(test_items, "skipped")
        unknown_ids = get_test_ids_by_status(test_items, "unknown")

        # Create combined list of all non-passing test IDs for filtering
        non_passing_ids = set(failed_ids + broken_ids + skipped_ids + unknown_ids)

        # Ensure passed tests don't appear in failed/broken categories (status precedence)
        passed_ids = [test_id for test_id in passed_ids if test_id not in non_passing_ids]

        # Remove failed tests from broken category (failed takes precedence over broken)
        broken_ids = [test_id for test_id in broken_ids if test_id not in failed_ids]

        # Compile final test statistics with categorized test IDs
        test_stats["total"] = all_tests
        test_stats["passed"] = passed_ids
        test_stats["failed"] = failed_ids
        test_stats["broken"] = broken_ids
        test_stats["skipped"] = skipped_ids
        test_stats["unknown"] = unknown_ids

        # Sort failed IDs and export results to JSON files for external consumption
        failed_ids.sort()
        write_failed_test_ids_to_file(failed_ids)
        write_passed_test_ids_to_file(passed_ids)

        print(f"Analysis complete: {len(all_tests)} unique tests processed")

    except Exception as e:
        print(f"Error in analysing test results: {e}")

    return test_stats


def write_failed_test_ids_to_file(failed_ids: List[str]) -> None:
    """
    Export failed test case IDs to a JSON file for external analysis.

    This function saves a sorted list of failed test case IDs to a JSON file,
    enabling integration with other tools for failure analysis, reporting, or
    automated remediation workflows.

    Args:
        failed_ids (List[str]): List of test case IDs that failed execution.
                               IDs should follow the format "T###" (e.g., "T001", "T123").

    Returns:
        None: This function does not return a value.

    Raises:
        None: All exceptions are caught internally and logged to console.

    Side Effects:
        - Creates or overwrites "failed_testscripts.json" in the JSON_FILE_PATH directory
        - Creates the output directory if it doesn't exist
        - Prints error messages to console if file operations fail

    Example:
        >>> failed_tests = ["T001", "T015", "T042", "T089"]
        >>> write_failed_test_ids_to_file(failed_tests)
        # Creates: json_files/failed_testscripts.json
        # Content: ["T001", "T015", "T042", "T089"]
    """
    try:
        # Ensure output directory exists
        os.makedirs(json_file_path, exist_ok=True)

        # Save failed test IDs to JSON file with proper formatting
        output_file = os.path.join(json_file_path, FAILED_TESTS_JSON)
        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(sorted(failed_ids), file, indent=4, ensure_ascii=False)
        print(f"Failed test IDs saved to: {output_file}")
    except Exception as e:
        print(f"Error saving failed test IDs to file: {e}")


def write_passed_test_ids_to_file(passed_ids: List[str]) -> None:
    """
    Export passed test case IDs to a JSON file for external analysis.

    This function saves a sorted list of passed test case IDs to a JSON file,
    enabling tracking of successful test executions and integration with other
    tools for success analysis or reporting purposes.

    Args:
        passed_ids (List[str]): List of test case IDs that passed execution.
                              IDs should follow the format "T###" (e.g., "T002", "T056").

    Returns:
        None: This function does not return a value.

    Raises:
        None: All exceptions are caught internally and logged to console.

    Side Effects:
        - Creates or overwrites "passed_testscripts.json" in the JSON_FILE_PATH directory
        - Creates the output directory if it doesn't exist
        - Prints error messages to console if file operations fail

    Example:
        >>> passed_tests = ["T002", "T003", "T056", "T078", "T099"]
        >>> write_passed_test_ids_to_file(passed_tests)
        # Creates: json_files/passed_testscripts.json
        # Content: ["T002", "T003", "T056", "T078", "T099"]
    """
    try:
        # Ensure output directory exists
        os.makedirs(json_file_path, exist_ok=True)

        # Save passed test IDs to JSON file with proper formatting
        output_file = os.path.join(json_file_path, PASSED_TESTS_JSON)
        with open(output_file, "w", encoding="utf-8") as file:
            json.dump(sorted(passed_ids), file, indent=4, ensure_ascii=False)
        print(f"Passed test IDs saved to: {output_file}")
    except Exception as e:
        print(f"Error saving passed test IDs to file: {e}")


def summarize_allure_report():
    """
    Command-line interface for Allure Report Summarizer.

    This block executes when the script is run directly (not imported as a module).
    It processes environment variables, locates the Allure report, and generates
    a summary of test execution results.
    """

    # Retrieve Allure report directory from environment variable
    allure_report_path = os.environ.get("ALLURE_REPORT_PATH")
    if not allure_report_path:
        print("ALLURE_REPORT_PATH environment variable is not set. Example: c:\\reports")
        exit(1)
    else:
        print(f"ALLURE_REPORT_PATH: {allure_report_path}")

    # Locate the HTML report file in the specified directory
    report_path = get_report_path(allure_report_path)

    # Process the report and generate summary
    if os.path.exists(report_path):
        print(f"Processing Allure report: {report_path}")
        summary = summarize_html_report(report_path)
        print("\n=== TEST EXECUTION SUMMARY ===")
        print(summary)
        print(f"\nSummary processing completed for: {report_path}")
    else:
        print(f"Allure report file not found: {report_path}")
        print(f"Please ensure the ALLURE_REPORT_PATH contains valid Allure HTML report files.")
        exit(1)


if __name__ == "__main__":
    summarize_allure_report()