#!/usr/bin/env python3
"""
Convert locations.json to use template-based interactables format.
This script converts the new format (full instance data) to old format (template_id + outcomes).
"""

import json
import sys

def convert_interactables_to_template_format(interactables_dict):
    """Convert interactables from full format to template format."""
    if not interactables_dict:
        return {}
    
    converted = {}
    
    for instance_id, instance_data in interactables_dict.items():
        # Check if already in template format
        if 'template_id' in instance_data:
            # Already in template format, keep as is
            converted[instance_id] = instance_data
            continue
        
        # Check if in new format with 'id' and 'actions'
        if 'id' in instance_data and 'actions' in instance_data:
            # Convert to template format
            template_id = instance_data['id']
            
            # Build outcomes from actions
            outcomes = {}
            for action_id, action_data in instance_data['actions'].items():
                outcome = {
                    'success_rate': 0.5,  # Default success rate
                    'stamina_cost': action_data.get('stamina_cost', 2),
                    'crit_success_chance': 0.1,
                    'crit_failure_chance': 0.1,
                    'text': {
                        'success': '',
                        'failure': '',
                        'crit_success': '',
                        'crit_failure': ''
                    },
                    'rewards': {
                        'items': [],
                        'damage': 0,
                        'crit_items': [],
                        'crit_damage': 0
                    }
                }
                
                # Extract text from outcomes if available
                if 'outcomes' in action_data:
                    if 'success' in action_data['outcomes']:
                        outcome['text']['success'] = action_data['outcomes']['success'].get('text', '')
                        # Convert items_reward to items list
                        items_reward = action_data['outcomes']['success'].get('items_reward', {})
                        for item_id, quantity in items_reward.items():
                            outcome['rewards']['items'].append({
                                'item_id': item_id,
                                'quantity': quantity,
                                'chance': 1.0
                            })
                        outcome['rewards']['damage'] = action_data['outcomes']['success'].get('damage_taken', 0)
                    
                    if 'failure' in action_data['outcomes']:
                        outcome['text']['failure'] = action_data['outcomes']['failure'].get('text', '')
                    
                    if 'critical_failure' in action_data['outcomes']:
                        outcome['text']['crit_failure'] = action_data['outcomes']['critical_failure'].get('text', '')
                        outcome['rewards']['crit_damage'] = action_data['outcomes']['critical_failure'].get('damage_taken', 0)
                
                outcomes[action_id] = outcome
            
            converted[instance_id] = {
                'template_id': template_id,
                'outcomes': outcomes
            }
        else:
            # Unknown format, keep as is
            converted[instance_id] = instance_data
    
    return converted

def main():
    # Load locations.json
    locations_file = 'gamedata/locations.json'
    
    try:
        with open(locations_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except Exception as e:
        print(f"Error loading {locations_file}: {e}")
        sys.exit(1)
    
    # Convert all location interactables
    locations_converted = 0
    interactables_converted = 0
    
    for location in data.get('locations', []):
        if 'interactables' in location and location['interactables']:
            original_count = len(location['interactables'])
            location['interactables'] = convert_interactables_to_template_format(location['interactables'])
            
            if original_count > 0:
                locations_converted += 1
                interactables_converted += original_count
    
    # Save back to file
    try:
        with open(locations_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)
        
        print(f"✅ Conversion complete!")
        print(f"   Processed {locations_converted} locations")
        print(f"   Converted {interactables_converted} interactables to template format")
    except Exception as e:
        print(f"❌ Error saving {locations_file}: {e}")
        sys.exit(1)

if __name__ == '__main__':
    main()
