"""
ENIGMA Inventario - API Routes FIXED
=====================================

Endpoints REST completi per inventario.

Author: HetGi & Claude  
Date: 2026-01-14 (FIXED VERSION)
"""

from flask import Blueprint, request, jsonify
from functools import wraps
import logging
import os

logger = logging.getLogger(__name__)

inventory_bp = Blueprint('inventory', __name__, url_prefix='/api/v1/inventory')


def require_auth(f):
    """Decorator auth (mock per demo)."""
    @wraps(f)
    def decorated(*args, **kwargs):
        request.user = {
            'id': 1,
            'tenant_id': 1,
            'email': 'demo@studium.it',
            'role': 'admin'
        }
        return f(*args, **kwargs)
    return decorated


def get_service():
    """Factory per InventoryService."""
    from service_inventory_fixed import create_inventory_service
    
    db_config = {
        'host': os.getenv('DB_HOST', 'localhost'),
        'user': os.getenv('DB_USER', 'enigma_user'),
        'password': os.getenv('DB_PASSWORD', 'arcana2026'),
        'database': os.getenv('DB_NAME', 'enigma')
    }
    
    api_key = os.getenv('CASSANOVA_API_KEY', '2bc78260-aef5-4779-968c-772801ca5543')
    
    return create_inventory_service(db_config, api_key)


# ============================================================================
# SINCRONIZZAZIONE PRODOTTI
# ============================================================================

@inventory_bp.route('/products/sync', methods=['POST'])
@require_auth
def sync_products():
    """
    Sincronizza TUTTI i prodotti da Cassanova.
    
    Returns:
        {
            "success": true,
            "data": {
                "total": 1234,
                "cached": 1230,
                "errors": 4
            }
        }
    """
    try:
        service = get_service()
        tenant_id = request.user['tenant_id']
        
        result = service.sync_all_products(tenant_id)
        
        return jsonify({
            'success': True,
            'data': result
        }), 200
    except Exception as e:
        logger.error(f"Errore sync: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


# ============================================================================
# RICERCA PRODOTTI
# ============================================================================

@inventory_bp.route('/products/search', methods=['GET'])
@require_auth
def search_products():
    """
    Cerca prodotti per barcode o nome.
    
    Query params:
        - barcode: Codice a barre
        - description: Nome prodotto
    
    Returns:
        {
            "success": true,
            "data": {
                "products": [...]
            }
        }
    """
    try:
        service = get_service()
        tenant_id = request.user['tenant_id']
        
        barcode = request.args.get('barcode')
        description = request.args.get('description')
        
        if not barcode and not description:
            return jsonify({
                'success': False,
                'error': 'Specificare barcode o description'
            }), 400
        
        products = service.search_product(tenant_id, barcode, description)
        
        return jsonify({
            'success': True,
            'data': {
                'products': products,
                'count': len(products)
            }
        }), 200
    except Exception as e:
        logger.error(f"Errore ricerca: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


# ============================================================================
# SESSIONI INVENTARIO
# ============================================================================

@inventory_bp.route('/session/start', methods=['POST'])
@require_auth
def start_session():
    """
    Avvia nuova sessione inventario.
    
    Body (opzionale):
        {"sede_id": 1}
    
    Returns:
        {
            "success": true,
            "data": {
                "session_id": 123,
                "session": {...}
            }
        }
    """
    try:
        service = get_service()
        user = request.user
        
        data = request.get_json() or {}
        sede_id = data.get('sede_id', 1)
        
        session_id = service.start_session(user['tenant_id'], user['id'], sede_id)
        
        if session_id:
            session_data = service.get_session_details(session_id, user['tenant_id'])
            return jsonify({
                'success': True,
                'data': {
                    'session_id': session_id,
                    'session': session_data
                }
            }), 201
        else:
            return jsonify({
                'success': False,
                'error': 'Sessione già aperta'
            }), 400
    except Exception as e:
        logger.error(f"Errore start: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@inventory_bp.route('/session/current', methods=['GET'])
@require_auth
def get_current_session():
    """Ottiene sessione corrente."""
    try:
        service = get_service()
        user = request.user
        
        session_data = service.get_current_session(user['tenant_id'], user['id'])
        
        if session_data:
            return jsonify({
                'success': True,
                'data': {'session': session_data}
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': 'Nessuna sessione aperta'
            }), 404
    except Exception as e:
        logger.error(f"Errore get current: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@inventory_bp.route('/session/close', methods=['POST'])
@require_auth
def close_session():
    """
    Chiude sessione corrente.
    
    Body (opzionale):
        {"note": "Inventario completato"}
    
    Returns:
        {"success": true}
    """
    try:
        service = get_service()
        user = request.user
        
        # Ottieni sessione corrente
        current = service.get_current_session(user['tenant_id'], user['id'])
        if not current:
            return jsonify({
                'success': False,
                'error': 'Nessuna sessione aperta'
            }), 400
        
        data = request.get_json() or {}
        note = data.get('note')
        
        success = service.close_session(current['id'], user['tenant_id'], note)
        
        if success:
            return jsonify({
                'success': True,
                'message': 'Sessione chiusa'
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': 'Errore chiusura sessione'
            }), 500
    except Exception as e:
        logger.error(f"Errore close: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@inventory_bp.route('/sessions/recent', methods=['GET'])
@require_auth
def get_recent_sessions():
    """Lista sessioni recenti."""
    try:
        service = get_service()
        tenant_id = request.user['tenant_id']
        limit = int(request.args.get('limit', 10))
        
        sessions = service.get_recent_sessions(tenant_id, limit)
        
        return jsonify({
            'success': True,
            'data': {
                'sessions': sessions,
                'count': len(sessions)
            }
        }), 200
    except Exception as e:
        logger.error(f"Errore get recent: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@inventory_bp.route('/session/<int:session_id>', methods=['GET'])
@require_auth
def get_session_detail(session_id):
    """Dettaglio sessione con items."""
    try:
        service = get_service()
        tenant_id = request.user['tenant_id']
        
        session_data = service.get_session_details(session_id, tenant_id)
        items = service.get_session_items(session_id, tenant_id)
        
        return jsonify({
            'success': True,
            'data': {
                'session': session_data,
                'items': items,
                'items_count': len(items)
            }
        }), 200
    except Exception as e:
        logger.error(f"Errore get detail: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


# ============================================================================
# SCANSIONE BARCODE
# ============================================================================

@inventory_bp.route('/scan', methods=['POST'])
@require_auth
def scan_barcode():
    """
    Scansiona barcode e aggiunge a sessione.
    
    Body:
        {
            "barcode": "8001234567890",
            "quantita": 1  // opzionale
        }
    
    Returns:
        {
            "success": true,
            "data": {
                "item_id": 456,
                "found_in_api": true,
                "product": {...}
            }
        }
    """
    try:
        service = get_service()
        user = request.user
        
        data = request.get_json()
        if not data or 'barcode' not in data:
            return jsonify({
                'success': False,
                'error': 'Campo barcode richiesto'
            }), 400
        
        barcode = data['barcode'].strip()
        quantita = data.get('quantita', 1)
        
        # Ottieni sessione corrente
        current = service.get_current_session(user['tenant_id'], user['id'])
        if not current:
            return jsonify({
                'success': False,
                'error': 'Nessuna sessione aperta. Avvia prima una sessione.'
            }), 400
        
        # Cerca prodotto
        products = service.search_product(user['tenant_id'], barcode=barcode)
        product_data = products[0] if products else None
        found_in_api = bool(product_data)
        
        # Aggiungi a sessione
        item_id = service.add_item(
            current['id'],
            user['tenant_id'],
            barcode,
            product_data,
            found_in_api,
            quantita
        )
        
        if item_id:
            response_data = {
                'item_id': item_id,
                'barcode': barcode,
                'found_in_api': found_in_api
            }
            if product_data:
                response_data['product'] = product_data
            
            message = 'Prodotto trovato e aggiunto' if found_in_api else 'Barcode registrato (non trovato)'
            
            return jsonify({
                'success': True,
                'data': response_data,
                'message': message
            }), 201
        else:
            return jsonify({
                'success': False,
                'error': 'Errore aggiunta item'
            }), 500
    except Exception as e:
        logger.error(f"Errore scan: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500


@inventory_bp.route('/item/<int:item_id>', methods=['DELETE'])
@require_auth
def delete_item(item_id):
    """Elimina item da sessione."""
    try:
        service = get_service()
        user = request.user
        
        # Ottieni sessione corrente
        current = service.get_current_session(user['tenant_id'], user['id'])
        if not current:
            return jsonify({
                'success': False,
                'error': 'Nessuna sessione aperta'
            }), 400
        
        success = service.delete_item(item_id, current['id'])
        
        if success:
            return jsonify({
                'success': True,
                'message': 'Item eliminato'
            }), 200
        else:
            return jsonify({
                'success': False,
                'error': 'Item non trovato o errore'
            }), 404
    except Exception as e:
        logger.error(f"Errore delete: {e}")
        return jsonify({'success': False, 'error': str(e)}), 500
