#!/usr/bin/env python3
"""
Automated script to update criteria weights in Python files
Called by the Criteria Manager UI via a simple web API
"""
import sys
import json
import re

def update_custom_criteria_weights(weights):
    """Update weights in custom_criteria.py"""

    criteria_map = {
        'rainfall': 'RainfallCriterion',
        'temperature': 'TemperatureCriterion',
        'climate': 'ClimateChangeCriterion',
        'airport': 'AirportDistanceCriterion',
        'rural': 'PopulationDensityCriterion',
        'soil': 'SoilQualityCriterion',
        'water': 'WaterAvailabilityCriterion',
        'airbnb': 'AirbnbRentabilityCriterion'
    }

    try:
        with open('custom_criteria.py', 'r') as f:
            content = f.read()

        # Update each criterion's weight
        for key, class_name in criteria_map.items():
            if key in weights:
                weight = float(weights[key])

                # Find the __init__ method for this criterion and update weight
                pattern = rf'(class {class_name}\(Criterion\):.*?def __init__\(self\):.*?self\.weight = )[0-9.]+'
                replacement = rf'\g<1>{weight}'
                content = re.sub(pattern, replacement, content, flags=re.DOTALL)

        # Write back
        with open('custom_criteria.py', 'w') as f:
            f.write(content)

        return True, "Custom criteria weights updated successfully"

    except Exception as e:
        return False, f"Error updating custom criteria: {str(e)}"


def update_gpt_criteria_weights(weights):
    """Update weights in analyze_from_urls.py"""

    criteria_map = {
        'market': 'regeneratieve market garden',
        'guest': 'gastenverblijf',
        'workshop': 'werkplaats',
        'rental': 'zelfstandige verhuureenheden',
        'location': 'locatie',
        'localmarket': 'afstand tot lokale markt'
    }

    try:
        with open('analyze_from_urls.py', 'r') as f:
            content = f.read()

        # Find the criteria_weights dictionary
        pattern = r'criteria_weights\s*=\s*\{[^}]+\}'
        match = re.search(pattern, content)

        if not match:
            return False, "Could not find criteria_weights in analyze_from_urls.py"

        # Build new dictionary
        new_weights = "criteria_weights = {\n"
        for key, dutch_name in criteria_map.items():
            if key in weights:
                weight = float(weights[key])
                new_weights += f'    "{dutch_name}": {weight},\n'
        new_weights = new_weights.rstrip(',\n') + '\n}'

        # Replace
        content = re.sub(pattern, new_weights, content)

        # Write back
        with open('analyze_from_urls.py', 'w') as f:
            f.write(content)

        return True, "GPT criteria weights updated successfully"

    except Exception as e:
        return False, f"Error updating GPT criteria: {str(e)}"


def main():
    """Main entry point - reads JSON config from stdin"""

    if len(sys.argv) < 2:
        print(json.dumps({
            'success': False,
            'message': 'Usage: python3 update_criteria_weights.py <config.json>'
        }))
        sys.exit(1)

    config_file = sys.argv[1]

    try:
        with open(config_file, 'r') as f:
            config = json.load(f)

        results = {}

        # Update custom criteria if provided
        if 'custom' in config:
            success, message = update_custom_criteria_weights(config['custom'])
            results['custom'] = {'success': success, 'message': message}

        # Update GPT criteria if provided
        if 'gpt' in config:
            success, message = update_gpt_criteria_weights(config['gpt'])
            results['gpt'] = {'success': success, 'message': message}

        # Return results
        all_success = all(r.get('success', False) for r in results.values())

        print(json.dumps({
            'success': all_success,
            'results': results
        }, indent=2))

        sys.exit(0 if all_success else 1)

    except Exception as e:
        print(json.dumps({
            'success': False,
            'message': f'Error: {str(e)}'
        }))
        sys.exit(1)


if __name__ == '__main__':
    main()
