"""Layer operations routes for ORA Editor."""

from flask import Blueprint, request, jsonify

from ora_editor.ora_ops import (
    load_ora, add_masked_layer, rename_layer, delete_layer,
    reorder_layer, set_layer_visibility
)

layers_bp = Blueprint('layers', __name__)


@layers_bp.route('/api/layers', methods=['GET'])
def api_layers():
    """Get the current layer structure."""
    ora_path = request.args.get('ora_path')
    
    if not ora_path:
        return jsonify({'success': False, 'error': 'Missing ora_path parameter'}), 400
    
    try:
        loaded = load_ora(ora_path)
        
        layers = []
        for layer in loaded['layers']:
            layers.append({
                'name': layer['name'],
                'src': layer['src'],
                'group': layer.get('group'),
                'visible': layer.get('visible', True)
            })
        
        return jsonify({'success': True, 'layers': layers})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@layers_bp.route('/api/layer/add', methods=['POST'])
def api_layer_add():
    """Add a new masked layer."""
    data = request.get_json()
    
    required = ['ora_path', 'entity_name', 'mask_path']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    ora_path = data['ora_path']
    entity_name = data['entity_name']
    mask_path = data['mask_path']
    source_layer = data.get('source_layer', 'base')
    
    result = add_masked_layer(ora_path, entity_name, mask_path, source_layer)
    
    return jsonify(result)


@layers_bp.route('/api/layer/rename', methods=['POST'])
def api_layer_rename():
    """Rename a layer."""
    data = request.get_json()
    
    required = ['ora_path', 'old_name', 'new_name']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    result = rename_layer(data['ora_path'], data['old_name'], data['new_name'])
    return jsonify(result)


@layers_bp.route('/api/layer/delete', methods=['POST'])
def api_layer_delete():
    """Delete a layer."""
    data = request.get_json()
    
    required = ['ora_path', 'layer_name']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    result = delete_layer(data['ora_path'], data['layer_name'])
    return jsonify(result)


@layers_bp.route('/api/layer/reorder', methods=['POST'])
def api_layer_reorder():
    """Reorder a layer."""
    data = request.get_json()
    
    required = ['ora_path', 'layer_name', 'direction']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    result = reorder_layer(data['ora_path'], data['layer_name'], data['direction'])
    return jsonify(result)


@layers_bp.route('/api/layer/visibility', methods=['POST'])
def api_layer_visibility():
    """Set layer visibility."""
    data = request.get_json()
    
    required = ['ora_path', 'layer_name', 'visible']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    result = set_layer_visibility(data['ora_path'], data['layer_name'], data['visible'])
    return jsonify(result)
