"""Polygon operations routes for ORA Editor."""

from flask import Blueprint, request, jsonify
import logging

from ora_editor.services import polygon_storage

logger = logging.getLogger(__name__)

polygon_bp = Blueprint('polygon', __name__)


@polygon_bp.route('/api/polygon', methods=['POST'])
def api_polygon():
    """Store polygon points for overlay."""
    data = request.get_json()
    
    required = ['ora_path', 'points']
    for field in required:
        if field not in data:
            return jsonify({'success': False, 'error': f'Missing {field} parameter'}), 400
    
    ora_path = data['ora_path']
    points = data['points']
    color = data.get('color', '#FF0000')
    width = data.get('width', 2)
    
    logger.info(f"[POLYGON] Storing polygon: {len(points)} points, color: {color}, width: {width}")
    
    polygon_storage.store(ora_path, points, color, width)
    
    return jsonify({
        'success': True,
        'overlay_url': f'/api/image/polygon?ora_path={ora_path}'
    })


@polygon_bp.route('/api/polygon/clear', methods=['POST'])
def api_polygon_clear():
    """Clear stored polygon points."""
    ora_path = request.json.get('ora_path') if request.data else None
    
    if ora_path:
        polygon_storage.clear(ora_path)
    
    return jsonify({'success': True})
