import json

def extract_distinct_trainers(input_file, output_file, max_trainers=100):
    try:
        # Load the Pokémon data from the input JSON file
        with open(input_file, 'r', encoding='utf-8') as file:
            pokemon_data = json.load(file)

        # Create a set to store distinct trainers
        distinct_trainers = set()

        # Extract trainers from the Pokémon data
        for pokemon in pokemon_data:
            for trainer in pokemon.get("ownedBy", []):
                distinct_trainers.add((trainer["name"], trainer["town"]))
                if len(distinct_trainers) >= max_trainers:
                    break
            if len(distinct_trainers) >= max_trainers:
                break

        # Convert the set to a list of dictionaries
        trainer_list = [{"name": name, "town": town} for name, town in distinct_trainers]

        # Save the distinct trainers to the output JSON file
        with open(output_file, 'w', encoding='utf-8') as file:
            json.dump(trainer_list, file, indent=4)

        print(f"Distinct trainers JSON has been saved to {output_file}")

    except FileNotFoundError:
        print(f"Error: File {input_file} not found.")
    except json.JSONDecodeError:
        print(f"Error: File {input_file} is not valid JSON.")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

# Specify input and output file paths
input_file = 'poke_data.json'  # Replace with your actual input file path
output_file = 'trainers.json'

# Call the function to process the trainers
extract_distinct_trainers(input_file, output_file)
