"""
Flask API Server for Scholarship Finder
Provides REST endpoints for scholarship data and recommendations
"""

from flask import Flask, jsonify, request
from flask_cors import CORS
import json
from datetime import datetime
from scholarship_scraper import ScholarshipScraper
from recommendation_model import get_user_recommendations, ScholarshipRecommender

app = Flask(__name__)
CORS(app)  # Enable CORS for Android app

# Initialize components
scraper = ScholarshipScraper()
recommender = ScholarshipRecommender()


@app.route('/')
def home():
    """API health check"""
    return jsonify({
        'status': 'running',
        'message': 'Scholarship Finder API',
        'version': '1.0.0',
        'timestamp': datetime.now().isoformat()
    })


@app.route('/api/scholarships', methods=['GET'])
def get_all_scholarships():
    """Get all available scholarships"""
    try:
        # Get query parameters for filtering
        category = request.args.get('category')
        source = request.args.get('source')
        limit = request.args.get('limit', 50, type=int)
        
        scholarships = recommender.scholarships
        
        # Apply filters
        if category:
            scholarships = [s for s in scholarships 
                          if category.lower() in str(s.get('eligibility_criteria', {}).get('category', [])).lower()
                          or category.lower() in s.get('category', '').lower()]
        
        if source:
            scholarships = [s for s in scholarships 
                          if source.lower() in s.get('source', '').lower()]
        
        return jsonify({
            'success': True,
            'count': len(scholarships[:limit]),
            'scholarships': scholarships[:limit]
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/scholarships/<int:scholarship_id>', methods=['GET'])
def get_scholarship_by_id(scholarship_id):
    """Get a specific scholarship by ID"""
    try:
        for scholarship in recommender.scholarships:
            if scholarship.get('id') == scholarship_id:
                return jsonify({
                    'success': True,
                    'scholarship': scholarship
                })
        
        return jsonify({
            'success': False,
            'error': 'Scholarship not found'
        }), 404
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/recommendations', methods=['POST'])
def get_recommendations():
    """Get personalized scholarship recommendations based on user profile"""
    try:
        user_data = request.get_json()
        
        if not user_data:
            return jsonify({
                'success': False,
                'error': 'User profile data required'
            }), 400
        
        # Get top N recommendations (default 10)
        top_n = user_data.get('top_n', 10)
        recommendations = get_user_recommendations(user_data, top_n)
        
        # Format response
        formatted_recs = []
        for rec in recommendations:
            formatted_recs.append({
                'id': rec['scholarship'].get('id'),
                'name': rec['scholarship'].get('name'),
                'amount': rec['scholarship'].get('amount'),
                'deadline': rec['scholarship'].get('deadline'),
                'description': rec['scholarship'].get('description'),
                'source': rec['scholarship'].get('source'),
                'eligibility_score': rec['eligibility_score'],
                'match_reason': rec['match_reason']
            })
        
        return jsonify({
            'success': True,
            'user_id': user_data.get('user_id'),
            'count': len(formatted_recs),
            'recommendations': formatted_recs
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/scrape', methods=['POST'])
def trigger_scrape():
    """Trigger a new scholarship scrape (admin endpoint)"""
    try:
        # Optional: Add authentication check here
        api_key = request.headers.get('X-API-Key')
        if api_key != 'your-secret-key':  # Replace with actual key
            return jsonify({
                'success': False,
                'error': 'Unauthorized'
            }), 401
        
        scraper_instance = ScholarshipScraper()
        scholarships = scraper_instance.scrape_all()
        scraper_instance.save_to_json()
        
        return jsonify({
            'success': True,
            'message': f'Scraped {len(scholarships)} scholarships',
            'count': len(scholarships)
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/search', methods=['GET'])
def search_scholarships():
    """Search scholarships by keyword"""
    try:
        query = request.args.get('q', '').lower()
        
        if not query:
            return jsonify({
                'success': False,
                'error': 'Search query required'
            }), 400
        
        results = []
        for scholarship in recommender.scholarships:
            # Search in name, description, and source
            name = scholarship.get('name', '').lower()
            description = scholarship.get('description', '').lower()
            source = scholarship.get('source', '').lower()
            
            if query in name or query in description or query in source:
                results.append(scholarship)
        
        return jsonify({
            'success': True,
            'query': query,
            'count': len(results),
            'results': results
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


@app.route('/api/categories', methods=['GET'])
def get_categories():
    """Get all available scholarship categories"""
    categories = ['SC', 'ST', 'OBC', 'General', 'Minority', 'Merit', 'Defence', 'Differently Abled']
    return jsonify({
        'success': True,
        'categories': categories
    })


@app.route('/api/eligible', methods=['POST'])
def check_eligibility():
    """Check if a user is eligible for a specific scholarship"""
    try:
        data = request.get_json()
        user_data = data.get('user')
        scholarship_id = data.get('scholarship_id')
        
        if not user_data or not scholarship_id:
            return jsonify({
                'success': False,
                'error': 'User data and scholarship_id required'
            }), 400
        
        # Find the scholarship
        scholarship = None
        for s in recommender.scholarships:
            if s.get('id') == scholarship_id:
                scholarship = s
                break
        
        if not scholarship:
            return jsonify({
                'success': False,
                'error': 'Scholarship not found'
            }), 404
        
        # Calculate eligibility
        from recommendation_model import UserProfile
        user = UserProfile(
            user_id=user_data.get('user_id', 0),
            name=user_data.get('name', ''),
            category=user_data.get('category', 'General'),
            income=float(user_data.get('income', 0)),
            current_class=user_data.get('current_class', '12'),
            percentage=float(user_data.get('percentage', 0)),
            gender=user_data.get('gender', ''),
            state=user_data.get('state', '')
        )
        
        score = recommender.calculate_eligibility_score(user, scholarship)
        
        return jsonify({
            'success': True,
            'scholarship_id': scholarship_id,
            'scholarship_name': scholarship.get('name'),
            'eligibility_score': score,
            'is_eligible': score >= 60,
            'message': 'Eligible' if score >= 60 else 'Not eligible based on current criteria'
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500


if __name__ == '__main__':
    print("Starting Scholarship Finder API Server...")
    print("API Documentation:")
    print("  GET  /                    - Health check")
    print("  GET  /api/scholarships    - Get all scholarships")
    print("  GET  /api/scholarships/<id> - Get scholarship by ID")
    print("  POST /api/recommendations - Get personalized recommendations")
    print("  GET  /api/search?q=<query> - Search scholarships")
    print("  GET  /api/categories      - Get categories")
    print("  POST /api/eligible        - Check eligibility")
    print("  POST /api/scrape          - Trigger scraping (admin)")
    
    app.run(host='0.0.0.0', port=5000, debug=True)