from __future__ import annotations import re from copy import deepcopy from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from modules.config.config import Config from modules.dat.process_dat import DatNode from modules.clone_lists.local_names import clone_list_local_names from modules.titletools import Removes, TraceTools from modules.utils import Font, eprint, pattern2string, regex_test def clone_list_variants( variant_titles: list[dict[str, Any]], variant_type: str, clone_list_group_contents: dict[str, Any], processed_titles: dict[str, set[DatNode]], quick_lookup: dict[str, dict[str, set[DatNode]]], missing_titles: set[str], deleted_titles: set[tuple[DatNode, str]], removed_titles: Removes, is_includes: bool, config: Config, report_on_match: bool, ) -> None: """ Looks up a variant from a clone list and modifies its DatNode entry accordingly. Args: variant_titles (list[dict[str, str]): The titles, supersets, or compilations array from a variants object in the clone list. variant_type (str): The type of variant being processed, either 'title', 'compilation', or 'superset'. clone_list_group_contents (dict[str, Any]): An entire group's contents from the clone list, including titles, compilations, and supersets. processed_titles (dict[str, set[DatNode]]): A work in progress dictionary of DatNodes, originally populated from the input DAT and actively being worked on by Retool. quick_lookup (dict[str, set[DatNode]]): A dictionary keyed by multiple title properties that enables quick lookup of titles. Due to the way Python references variables, changes made here are also reflected in `processed_titles`. missing_titles (set[str]): Somewhere to store searched for names that aren't found in the DAT file when going through `variant_titles`. These are reported as not found if the user has clone list warnings turned on. deleted_titles (set[tuple[DatNode, str]]): When titles listed in a clone list are processed, a new title is created to make the relevant changes. The original titles are added to this set, which is iterated over after this function has completed to remove the old titles from processed_titles. removed_titles (Removes): The Retool removes object, which contains and categorizes all the titles that have been removed from consideration. It is used for recovering titles defined by user includes, stats, and other output files generated by Retool. is_includes (bool, optional): Set to `True` when processing includes. Is only used to produce reliable reporting when performing a trace. config (Config): The Retool config object. report_on_match (bool): Whether Retool needs to report any titles being traced. """ variants: list[DatNode] = [] variant_name: str = '' for variant_title in variant_titles: if 'searchTerm' not in variant_title: eprint( f'• The following variants entry is missing a ' f'{Font.b}searchTerm{Font.be} key and will be skipped:', level='warning', ) eprint(f'\n {variant_title}', level='warning') if config.user_input.warningpause: eprint(pause=True) continue else: variant_name = variant_title['searchTerm'] name_type: str = '' if 'nameType' in variant_title: name_type = variant_title['nameType'] if not ( name_type == 'full' or name_type == 'short' or name_type == 'regionFree' or name_type == 'regex' ): name_type = 'short' else: name_type = 'short' # Look up the title in the dictionary, then process the required changes found_titles: set[DatNode] = set() if name_type == 'regex': valid_regex: list[str] = regex_test([variant_name], 'variants', 'clone list') if not valid_regex: continue for full_name in quick_lookup['full_name_index']: if pattern2string(re.compile(variant_name.lower()), full_name.lower()): found_titles = found_titles | quick_lookup['full_name_index'][full_name] elif name_type == 'full': if variant_name in quick_lookup['full_name_index']: found_titles = quick_lookup['full_name_index'][variant_name] elif name_type == 'short': if variant_name.lower() in quick_lookup['short_name_index']: found_titles = quick_lookup['short_name_index'][variant_name.lower()] elif name_type == 'regionFree': if variant_name in quick_lookup['region_free_name_index']: found_titles = quick_lookup['region_free_name_index'][variant_name] old_group_names: set[str] = set() for title in found_titles: old_group_names.add(title.group_name) new_group_name: str = clone_list_group_contents['group'].lower() if new_group_name not in processed_titles: processed_titles[new_group_name] = set() # If the title's not found in the DAT, add it to missing_titles, # otherwise add it to the delete list, then move it to the new # group with any new properties defined by the clone list if not found_titles: missing_titles.add(variant_name) else: if config.user_input.trace: report_on_match = TraceTools.trace_enable( set(found_titles), config.user_input.trace ) for title in found_titles: # Manage ignores if 'ignore' in variant_title: if isinstance(variant_title['ignore'], bool): if variant_title['ignore']: if title in processed_titles[title.group_name]: if report_on_match: eprint('') TraceTools.trace_title('REF0054') eprint( f'- Remove: {title.full_name}', wrap=False, level='disabled', pause=True, ) processed_titles[title.group_name].remove(title) title.exclude_reason = 'Clone list remove' removed_titles.clone_list_ignores.add(title) else: if config.user_input.verbose: eprint( f'• The following variant title\'s ' f'{Font.b}ignore{Font.be} key isn\'t a boolean, so it ' 'has been kept:', level='warning', ) eprint( f'\n {variant_title["searchTerm"]}', level='warning', wrap=False, ) if config.user_input.warningpause: eprint(pause=True) # Manage categories if 'categories' in variant_title: if isinstance(variant_title['categories'], list): if title in processed_titles[title.group_name]: if report_on_match: eprint('') TraceTools.trace_title('REF0053') eprint(f'• {title.full_name}', wrap=False) eprint( f' New categories: {variant_title["categories"]}\n{Font.disabled} Old categories: {title.categories}{Font.end}', wrap=False, pause=True, ) title.categories = variant_title['categories'] else: if config.user_input.verbose: eprint( f'• The following variant title\'s ' f'{Font.b}categories{Font.be} key isn\'t an array, so ' 'no category has been assigned:', level='warning', ) eprint( f'\n {variant_title["searchTerm"]}', level='warning', wrap=False, ) if config.user_input.warningpause: eprint(pause=True) # Work through the remaining variants for old_group_name in old_group_names: if title in processed_titles[old_group_name]: if variant_type == 'title' or variant_type == 'superset': new_title: DatNode = deepcopy(title) if 'priority' in variant_title: if new_title.clonelist_priority == 1: new_title.clonelist_priority = variant_title['priority'] if variant_type == 'superset': new_title.is_superset = True for old_group_name in old_group_names: if title in processed_titles[old_group_name]: deleted_titles.add((title, old_group_name)) # Manage local names if 'localNames' in variant_title: clone_list_local_names( variant_title, new_title, config, report_on_match ) # Manage English-friendly titles if 'englishFriendly' in variant_title: if isinstance(variant_title['englishFriendly'], bool): if variant_title['englishFriendly']: if title in processed_titles[title.group_name]: if report_on_match: eprint('') TraceTools.trace_title('REF0112') eprint(f'• {new_title.full_name}', wrap=False) if config.user_input.warningpause: eprint(pause=True) if 'En' not in new_title.languages: new_title.languages = ( *new_title.languages, 'En', ) # Manage oldest titles if 'isOldest' in variant_title: if isinstance(variant_title['isOldest'], bool): if variant_title['isOldest']: if title in processed_titles[title.group_name]: if report_on_match: eprint('') TraceTools.trace_title('REF0129') eprint(f'• {new_title.full_name}', wrap=False) if config.user_input.warningpause: eprint(pause=True) new_title.is_oldest = True # Manage filters if 'filters' in variant_title: # Check if at least one `conditions` and `results` keys exist exception_condition_found: bool = False exception_result_found: bool = False try: variant_title['filters'][0]['conditions'] exception_condition_found = True except Exception: pass try: variant_title['filters'][0]['results'] exception_result_found = True except Exception: pass exception_error_message: str = '' if not exception_condition_found and not exception_result_found: exception_error_message = 'conditions and results object' elif not exception_condition_found: exception_error_message = 'conditions object' elif not exception_result_found: exception_error_message = 'results object' if exception_error_message: eprint( f'• The following variant title\'s ' f'{Font.b}filters{Font.be} array is missing a {exception_error_message}, ' 'so no changes have been made:', level='warning', ) eprint( f'\n {variant_title["searchTerm"]}', level='warning', wrap=False, ) if config.user_input.warningpause: eprint(pause=True) # Make sure all filters are true for them to be processed if exception_condition_found and exception_result_found: for filter_condition in variant_title['filters']: condition_match_languages: bool = True condition_match_regions: bool = True condition_match_string: bool = True condition_region_order: bool = True if 'matchLanguages' in filter_condition['conditions']: if not all( x in title.languages for x in filter_condition['conditions'][ 'matchLanguages' ] ): condition_match_languages = False if 'matchRegions' in filter_condition['conditions']: if not all( x in title.regions for x in filter_condition['conditions'][ 'matchRegions' ] ): condition_match_regions = False if 'matchString' in filter_condition['conditions']: if not pattern2string( re.compile( filter_condition['conditions']['matchString'] ), title.full_name, ): condition_match_string = False if 'regionOrder' in filter_condition['conditions']: # Look for the regions that need to be higher in priority than # those defined in "higher than" if ( 'higherRegions' in filter_condition['conditions']['regionOrder'] ): regions: list[str] = filter_condition['conditions'][ 'regionOrder' ]['higherRegions'] else: eprint( f'• The following exception\'s ' f'{Font.b}higherRegions{Font.be} key isn\'t an array and will be ' 'skipped:', level='warning', ) eprint( f'\n {clone_list_group_contents["searchTerm"]}', level='warning', wrap=False, ) if config.user_input.warningpause: eprint(pause=True) # Look for the regions that need to be lower in priority than the # those defined in "region" if ( 'lowerRegions' in filter_condition['conditions']['regionOrder'] ): higher_than_regions: list[str] = filter_condition[ 'conditions' ]['regionOrder']['lowerRegions'] else: eprint( f'• The following exception\'s ' f'{Font.b}lowerRegions{Font.be} key isn\'t an array and will be ' 'skipped:', level='warning', ) eprint( f'\n {clone_list_group_contents["searchTerm"]}', level='warning', wrap=False, ) if config.user_input.warningpause: eprint(pause=True) # Check if a system config is in play region_order: list[str] = config.region_order_user if config.system_region_order_user: if { 'override': 'true' } in config.system_region_order_user: region_order = [ str(x) for x in config.system_region_order_user if 'override' not in x ] # Parse the "All other regions" entry if ( "All other regions" in regions and "All other regions" in higher_than_regions ): eprint( f'• The following exception has ' f'{Font.b}All other regions{Font.be} in both the ' f'{Font.b}higherRegions{Font.be} and ' f'{Font.b}lowerRegions{Font.be} keys, and will be skipped:', level='warning', ) eprint( f'\n {clone_list_group_contents["searchTerm"]}', level='warning', ) if config.user_input.warningpause: eprint(pause=True) continue # Fix UK problem if 'UK' in regions: if 'United Kingdom' not in regions: regions.append('United Kingdom') if 'United Kingdom' in regions: if 'UK' not in regions: regions.append('UK') if 'UK' in higher_than_regions: if 'United Kingdom' not in higher_than_regions: higher_than_regions.append('United Kingdom') if 'United Kingdom' in higher_than_regions: if 'UK' not in higher_than_regions: higher_than_regions.append('UK') # Import all other regions if needed if regions == ["All other regions"]: regions = [ x for x in config.region_order_default if x not in higher_than_regions ] if higher_than_regions == ["All other regions"]: higher_than_regions = [ x for x in config.region_order_default if x not in regions ] # Check that the regions are available in the user's current region # order, and store their priority if so higher_regions: list[int] = [ i for i, region in enumerate(region_order) if region in regions ] lower_regions: list[int] = [ i for i, region in enumerate(region_order) if region in higher_than_regions ] # If any of the higher regions is higher than ALL of the lower regions, # mark the condition as true if higher_regions and lower_regions: lower_regions_lowest: int = int( sorted(lower_regions)[0] ) condition_region_order = False for higher_region in higher_regions: if higher_region < lower_regions_lowest: condition_region_order = True else: condition_region_order = False if ( condition_match_languages and condition_match_regions and condition_match_string and condition_region_order ): if 'categories' in filter_condition['results']: if report_on_match: eprint('') TraceTools.trace_title('REF0108') eprint(f'• {title.full_name}', wrap=False) eprint( f' New categories: {variant_title["categories"]}\n{Font.disabled} Old categories: {title.categories}{Font.end}', wrap=False, pause=True, ) new_title.categories = filter_condition['results'][ 'categories' ] if 'group' in filter_condition['results']: if not new_title.group_moved_by_condition: if ( report_on_match and new_title.group_name != filter_condition['results'][ 'group' ].lower() and not is_includes ): eprint('') TraceTools.trace_title('REF0109') eprint(f'• {new_title.full_name}') eprint( f' New group: {filter_condition["results"]["group"].lower()}\n{Font.disabled} Old group: {new_title.group_name}{Font.end}', wrap=False, pause=True, ) new_title.group_name_conditional = ( filter_condition['results']['group'].lower() ) new_title.group_moved_by_condition = True if 'localNames' in filter_condition['results']: if report_on_match: eprint('') TraceTools.trace_title('REF0115') eprint( f' New name: {new_title.local_name}\n{Font.disabled} Old name: {new_title.full_name}{Font.end}', wrap=False, pause=True, ) clone_list_local_names( filter_condition['results'], new_title, config, report_on_match, ) if 'englishFriendly' in filter_condition['results']: if isinstance( filter_condition['results']['englishFriendly'], bool, ): if filter_condition['results'][ 'englishFriendly' ]: if report_on_match: eprint('') TraceTools.trace_title('REF0113') eprint( f'• {new_title.full_name}', wrap=False, ) if 'En' not in title.languages: new_title.languages = ( *new_title.languages, 'En', ) if 'isOldest' in filter_condition['results']: if isinstance( filter_condition['results']['isOldest'], bool ): if filter_condition['results']['isOldest']: if report_on_match: eprint('') TraceTools.trace_title('REF0132') eprint( f'• {new_title.full_name}', wrap=False, ) new_title.is_oldest = True if 'priority' in filter_condition['results']: if report_on_match: eprint('') TraceTools.trace_title('REF0110') eprint(f'• {new_title.full_name}', wrap=False) eprint( f' New priority: {filter_condition["results"]["priority"]}\n{Font.disabled} Old priority: {new_title.clonelist_priority}{Font.end}', pause=True, ) new_title.clonelist_priority = filter_condition[ 'results' ]['priority'] if 'superset' in filter_condition['results']: if filter_condition['results']['superset']: if report_on_match: eprint('') TraceTools.trace_title('REF0116') eprint( f'• {title.full_name}', wrap=False, pause=True, ) new_title.is_superset = True variants.append(new_title) elif variant_type == 'compilation': for compilation_title in processed_titles[old_group_name]: if compilation_title.full_name == title.full_name: title_position: int = 1 if 'titlePosition' in variant_title: title_position = variant_title['titlePosition'] if 'priority' in variant_title: clonelist_priority: int = variant_title['priority'] else: clonelist_priority = 1 compilation_title.contains_titles[ clone_list_group_contents['group'] ] = { "position": title_position, "priority": clonelist_priority, } if 'localNames' in variant_title: clone_list_local_names( variant_title, compilation_title, config, report_on_match, ) # Set these variant properties after the processing, to make sure they # don't mess with title look ups for variant in variants: if variant.group_name_conditional: variant.group_name = variant.group_name_conditional variant.short_name = variant.group_name_conditional.lower() if variant.group_name_conditional not in processed_titles: processed_titles[variant.group_name_conditional] = set() processed_titles[variant.group_name_conditional].add(variant) else: if report_on_match and variant.group_name != new_group_name and not is_includes: TraceTools.trace_title('REF0055') eprint(f'• {variant.full_name}', wrap=False) eprint(f' New group: {new_group_name}', wrap=False) eprint( f' Old group: {variant.group_name}', wrap=False, level='disabled', pause=True, ) variant.group_name = new_group_name variant.short_name = clone_list_group_contents['group'].lower() processed_titles[new_group_name].add(variant)