"""
Analytics Routes
API endpoints for worker and client analytics
"""

from flask import jsonify, request, render_template
from flask_login import login_required, current_user
from flask_jwt_extended import jwt_required, get_jwt_identity
from . import analytics_bp
from app.services.analytics_service import AnalyticsService
from functools import wraps
import csv
import io
from flask import Response


def get_user_id():
    """Get user ID from either Flask-Login or JWT"""
    if current_user and hasattr(current_user, 'is_authenticated') and current_user.is_authenticated:
        return current_user.id
    try:
        return get_jwt_identity()
    except:
        return None


def auth_required(f):
    """Decorator that works with either Flask-Login or JWT"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        user_id = get_user_id()
        if not user_id:
            return jsonify({'error': 'Authentication required'}), 401
        return f(*args, **kwargs)
    return decorated_function


# Web Routes for Analytics Pages

@analytics_bp.route('/worker', methods=['GET'])
@login_required
def worker_analytics_page():
    """Render the worker analytics page"""
    return render_template('analytics/worker.html')


@analytics_bp.route('/client', methods=['GET'])
@login_required
def client_analytics_page():
    """Render the client analytics page"""
    return render_template('analytics/client.html')


# API Routes for Analytics Data


@analytics_bp.route('/api/worker/<int:user_id>', methods=['GET'])
@auth_required
def get_worker_analytics(user_id):
    """Get comprehensive analytics for a worker"""
    try:
        # Check if current user has permission to view these analytics
        current_user_id = get_user_id()
        if current_user_id != user_id:
            # Could add admin check here
            return jsonify({'error': 'Unauthorized to view these analytics'}), 403
        
        analytics = AnalyticsService.get_worker_analytics(user_id)
        return jsonify({
            'success': True,
            'data': analytics
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/client/<int:user_id>', methods=['GET'])
@auth_required
def get_client_analytics(user_id):
    """Get comprehensive analytics for a client"""
    try:
        # Check if current user has permission to view these analytics
        current_user_id = get_user_id()
        if current_user_id != user_id:
            # Could add admin check here
            return jsonify({'error': 'Unauthorized to view these analytics'}), 403
        
        analytics = AnalyticsService.get_client_analytics(user_id)
        return jsonify({
            'success': True,
            'data': analytics
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/earnings', methods=['GET'])
@auth_required
def get_worker_earnings(user_id):
    """Get earnings over time for a worker"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        days = request.args.get('days', 30, type=int)
        earnings = AnalyticsService.get_earnings_over_time(user_id, days)
        
        return jsonify({
            'success': True,
            'data': earnings
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/completion-rate', methods=['GET'])
@auth_required
def get_worker_completion_rate(user_id):
    """Get job completion rate for a worker"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        completion_rate = AnalyticsService.get_job_completion_rate(user_id)
        
        return jsonify({
            'success': True,
            'data': completion_rate
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/services', methods=['GET'])
@auth_required
def get_worker_services(user_id):
    """Get popular services for a worker"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        services = AnalyticsService.get_popular_services(user_id)
        
        return jsonify({
            'success': True,
            'data': services
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/peak-hours', methods=['GET'])
@auth_required
def get_worker_peak_hours(user_id):
    """Get peak hours analysis for a worker"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        peak_hours = AnalyticsService.get_peak_hours_analysis(user_id)
        
        return jsonify({
            'success': True,
            'data': peak_hours
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/retention', methods=['GET'])
@auth_required
def get_worker_retention(user_id):
    """Get customer retention metrics for a worker"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        retention = AnalyticsService.get_customer_retention(user_id)
        
        return jsonify({
            'success': True,
            'data': retention
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/client/<int:user_id>/spending', methods=['GET'])
@auth_required
def get_client_spending(user_id):
    """Get spending patterns for a client"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        months = request.args.get('months', 12, type=int)
        spending = AnalyticsService.get_spending_patterns(user_id, months)
        
        return jsonify({
            'success': True,
            'data': spending
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/client/<int:user_id>/workers', methods=['GET'])
@auth_required
def get_client_workers(user_id):
    """Get favorite workers for a client"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        workers = AnalyticsService.get_favorite_workers(user_id)
        
        return jsonify({
            'success': True,
            'data': workers
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/client/<int:user_id>/success-rate', methods=['GET'])
@auth_required
def get_client_success_rate(user_id):
    """Get project success rate for a client"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        success_rate = AnalyticsService.get_project_success_rate(user_id)
        
        return jsonify({
            'success': True,
            'data': success_rate
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


# Export endpoints for CSV download

@analytics_bp.route('/api/worker/<int:user_id>/export/earnings', methods=['GET'])
@auth_required
def export_worker_earnings(user_id):
    """Export earnings data as CSV"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        days = request.args.get('days', 30, type=int)
        earnings = AnalyticsService.get_earnings_over_time(user_id, days)
        
        # Create CSV
        output = io.StringIO()
        writer = csv.DictWriter(output, fieldnames=['date', 'earnings', 'cumulative', 'jobs'])
        writer.writeheader()
        writer.writerows(earnings)
        
        # Create response
        response = Response(output.getvalue(), mimetype='text/csv')
        response.headers["Content-Disposition"] = f"attachment; filename=earnings_{user_id}.csv"
        
        return response
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/worker/<int:user_id>/export/all', methods=['GET'])
@auth_required
def export_worker_analytics(user_id):
    """Export all worker analytics as CSV"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        analytics = AnalyticsService.get_worker_analytics(user_id)
        
        # Create multi-section CSV
        output = io.StringIO()
        
        # Summary section
        output.write("WORKER ANALYTICS SUMMARY\n")
        output.write(f"Total Earnings,{analytics['summary']['total_earnings']}\n")
        output.write(f"Total Jobs,{analytics['summary']['total_jobs']}\n")
        output.write(f"Average Rating,{analytics['summary']['avg_rating']}\n")
        output.write(f"Monthly Earnings,{analytics['summary']['monthly_earnings']}\n")
        output.write("\n")
        
        # Completion Rate section
        output.write("JOB COMPLETION STATISTICS\n")
        completion = analytics['completion_rate']
        output.write(f"Total Jobs,{completion['total_jobs']}\n")
        output.write(f"Completed,{completion['completed']}\n")
        output.write(f"Cancelled,{completion['cancelled']}\n")
        output.write(f"Active,{completion['active']}\n")
        output.write(f"Completion Rate,{completion['completion_rate']}%\n")
        output.write("\n")
        
        # Customer Retention section
        output.write("CUSTOMER RETENTION\n")
        retention = analytics['customer_retention']
        output.write(f"Unique Clients,{retention['unique_clients']}\n")
        output.write(f"Repeat Clients,{retention['repeat_clients']}\n")
        output.write(f"Retention Rate,{retention['retention_rate']}%\n")
        output.write("\n")
        
        # Popular Services section
        output.write("POPULAR SERVICES\n")
        output.write("Service,Job Count,Total Revenue,Avg Job Value,Avg Rating\n")
        for service in analytics['popular_services']:
            output.write(f"{service['service']},{service['job_count']},{service['total_revenue']},{service['avg_job_value']},{service['avg_rating']}\n")
        
        # Create response
        response = Response(output.getvalue(), mimetype='text/csv')
        response.headers["Content-Disposition"] = f"attachment; filename=analytics_{user_id}.csv"
        
        return response
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@analytics_bp.route('/api/client/<int:user_id>/export/all', methods=['GET'])
@auth_required
def export_client_analytics(user_id):
    """Export all client analytics as CSV"""
    try:
        current_user_id = get_user_id()
        if current_user_id != user_id:
            return jsonify({'error': 'Unauthorized'}), 403
        
        analytics = AnalyticsService.get_client_analytics(user_id)
        
        # Create multi-section CSV
        output = io.StringIO()
        
        # Summary section
        output.write("CLIENT ANALYTICS SUMMARY\n")
        output.write(f"Total Spent,{analytics['summary']['total_spent']}\n")
        output.write(f"Total Projects,{analytics['summary']['total_projects']}\n")
        output.write(f"Active Projects,{analytics['summary']['active_projects']}\n")
        output.write(f"Monthly Spending,{analytics['summary']['monthly_spending']}\n")
        output.write("\n")
        
        # Favorite Workers section
        output.write("FAVORITE WORKERS\n")
        output.write("Worker Name,Projects Together,Total Paid,Avg Rating\n")
        for worker in analytics['favorite_workers']:
            output.write(f"{worker['name']},{worker['projects_together']},{worker['total_paid']},{worker['avg_rating']}\n")
        output.write("\n")
        
        # Project Success section
        output.write("PROJECT SUCCESS BY CATEGORY\n")
        output.write("Category,Total Projects,Success Rate,Avg Satisfaction\n")
        for category in analytics['project_success']:
            output.write(f"{category['category']},{category['total_projects']},{category['success_rate']}%,{category['avg_satisfaction']}\n")
        
        # Create response
        response = Response(output.getvalue(), mimetype='text/csv')
        response.headers["Content-Disposition"] = f"attachment; filename=client_analytics_{user_id}.csv"
        
        return response
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500
