# extract.py
#
# Given a specified JSON or gzipped JZON test file, this utility will extract
# a specific test specified either by decimal index or hexadecimal hash 
# (test_hash key must have been created by the addhash.py tool or otherwise 
# generated by a test suite)
#
# The test, if found, will be exported to the path specified by the third 
# argument.

import json
import sys
import re
import gzip

def is_test_index(value):
    """Check if the given value is a test index based on its format."""
    return re.match("^\d+$", value)

def extract_test_from_file(file_path, value):
    """Extract a test from the JSON or gzipped JSON file based on the test index or test_hash."""

    data = None

    # Check if the file is gzipped and load the content accordingly
    if file_path.endswith('.gz'):
        with gzip.open(file_path, 'rt', encoding='utf-8') as f:
            try:
                data = json.load(f)
            except json.JSONDecodeError:
                print("The provided file is not a valid gzipped JSON.")
    else:
        with open(file_path, 'r') as f:
            try:
                data = json.load(f)
            except json.JSONDecodeError:
                print("The provided file is not a valid JSON.")

    if data and isinstance(data, list):
        if is_test_index(value):  # If the provided value is an index
            idx = int(value)
            if 0 <= idx < len(data):
                return data[idx]
            else:
                print(f"Test index {idx} is out of range for the provided file.")
        else:  # If the provided value is a test_hash
            for obj in data:
                if obj.get('test_hash') == value:
                    return obj
            print(f"No test found with test_hash: {value} in the provided file.")

    return None

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: extract.py <test_path> <test_index_or_hash> <output_file>")
        sys.exit(1)

    test_path = sys.argv[1]
    test_value = sys.argv[2]
    output_file = sys.argv[3]

    # Extract the test based on index or hash
    test_obj = extract_test_from_file(test_path, test_value)
    
    if test_obj:
        with open(output_file, 'w') as f_out:
            json.dump(test_obj, f_out, indent=4)

        print(f"Test {test_value} extracted and saved to {output_file}.")