"""
Production health check and readiness endpoints
"""

from flask import Blueprint, jsonify
from app.extensions import db
from datetime import datetime
import os

health_bp = Blueprint('health', __name__)

@health_bp.route('/_health')
@health_bp.route('/_internal/health')
def health_check():
    """Basic health check endpoint"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.utcnow().isoformat(),
        'service': 'rateright',
        'version': os.environ.get('APP_VERSION', '1.0.0')
    }), 200

@health_bp.route('/_ready')
@health_bp.route('/_internal/ready')
def readiness_check():
    """Readiness check - includes database connectivity"""
    try:
        # Test database connection
        db.session.execute('SELECT 1')
        db_status = 'connected'
        db_error = None
    except Exception as e:
        db_status = 'error'
        db_error = str(e)
    
    is_ready = db_status == 'connected'
    
    response = {
        'ready': is_ready,
        'timestamp': datetime.utcnow().isoformat(),
        'checks': {
            'database': {
                'status': db_status,
                'error': db_error
            }
        }
    }
    
    return jsonify(response), 200 if is_ready else 503

@health_bp.route('/_internal/status')
def status():
    """Detailed status endpoint for monitoring"""
    try:
        # Count tables
        result = db.session.execute(
            "SELECT COUNT(*) FROM sqlite_master WHERE type='table'"
        )
        table_count = result.scalar()
        
        # Count users
        from app.models.user import User
        user_count = User.query.count()
        
        return jsonify({
            'status': 'operational',
            'timestamp': datetime.utcnow().isoformat(),
            'database': {
                'connected': True,
                'tables': table_count,
                'users': user_count
            },
            'environment': os.environ.get('FLASK_ENV', 'production'),
            'debug_mode': os.environ.get('FLASK_DEBUG', 'false') == 'true'
        }), 200
    except Exception as e:
        return jsonify({
            'status': 'error',
            'timestamp': datetime.utcnow().isoformat(),
            'error': str(e)
        }), 503
