from flask import Flask, request, jsonify
from flask_cors import CORS
from config import Config
from auth import require_auth
from validators import validate_date_range, validate_account_types, format_date_for_db, parse_date
from services import AsistenciaService
import logging
import os

app = Flask(__name__)
app.config.from_object(Config)
CORS(app)

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@app.route('/health', methods=['GET'])
def health():
    return jsonify({'status': 'ok'}), 200

@app.route('/api/v1/asistencia/resumen', methods=['POST'])
@require_auth
def get_resumen_asistencia():
    try:
        data = request.get_json()
        
        if not data:
            return jsonify({'error': 'Request body is required'}), 400
        
        fecha_range = data.get('fecha')
        id_nodo = data.get('idNodo')
        
        if not fecha_range:
            return jsonify({'error': 'fecha is required (format: dd-mm-yyyy - dd-mm-yyyy)'}), 400
        
        if id_nodo is None:
            id_nodo = 26338
        
        account_types = '2,4'
        
        fecha_parts = fecha_range.split(' - ')
        if len(fecha_parts) != 2:
            return jsonify({'error': 'fecha format must be: dd-mm-yyyy - dd-mm-yyyy'}), 400
        
        start_date_str = fecha_parts[0].strip()
        end_date_str = fecha_parts[1].strip()
        
        is_valid, error = validate_date_range(start_date_str, end_date_str)
        if not is_valid:
            return jsonify({'error': error}), 400
        
        start_date = parse_date(start_date_str)
        end_date = parse_date(end_date_str)
        
        fecha_inicio = format_date_for_db(start_date)
        fecha_fin = format_date_for_db(end_date)
        
        service = AsistenciaService()
        service.connect()
        
        try:
            colaboradores = service.get_colaboradores(
                id_nodo, 
                account_types
            )
            
            if not colaboradores:
                service.close()
                return jsonify({
                    'data': [],
                    'count': 0,
                    'message': 'No employees found for the given criteria'
                }), 200
            
            resultados = service.procesar_asistencia(
                colaboradores,
                fecha_inicio,
                fecha_fin
            )
            
            service.close()
            
            return jsonify({
                'data': resultados,
                'count': len(resultados),
                'filters': {
                    'fecha_inicio': start_date_str,
                    'fecha_fin': end_date_str,
                    'id_nodo': id_nodo
                }
            }), 200
        
        except Exception as e:
            service.close()
            logger.error(f"Error processing asistencia: {str(e)}")
            return jsonify({'error': f'Error processing request: {str(e)}'}), 500
    
    except Exception as e:
        logger.error(f"Error in get_resumen_asistencia: {str(e)}")
        return jsonify({'error': f'Internal server error: {str(e)}'}), 500

@app.errorhandler(404)
def not_found(error):
    return jsonify({'error': 'Endpoint not found'}), 404

@app.errorhandler(405)
def method_not_allowed(error):
    return jsonify({'error': 'Method not allowed'}), 405

@app.errorhandler(500)
def internal_error(error):
    logger.error(f"Internal server error: {str(error)}")
    return jsonify({'error': 'Internal server error'}), 500

if __name__ == '__main__':
    port = int(os.getenv('FLASK_PORT', 5000))
    app.run(host='0.0.0.0', port=port, debug=Config.FLASK_DEBUG)
