#!/usr/bin/env python3
"""
Fix dashboard navigation issues:
1. Add /my-jobs route for viewing user's jobs
2. Add /earnings route that redirects to workers analytics
3. Fix /logout redirect to go to /login
4. Fix /profile database queries
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
def create_navigation_fixes():
    """Create fixes for navigation issues"""
    # 1. Create the my-jobs route fix
    my_jobs_route_code = '''
# Add this to app/routes.py after the dashboard route (around line 475)
@app.route('/my-jobs')
@login_required
def my_jobs():
    """Display user's jobs"""
    try:
        # Get jobs based on user role
        if current_user.role == 'employer':
            # Employer sees jobs they've posted
            jobs = Job.query.filter_by(employer_id=current_user.id).order_by(Job.created_at.desc()).all()
            template = 'employer_jobs.html'
        else:
            # Worker sees jobs they're working on
            contracts = Contract.query.filter_by(
                worker_id=current_user.id
            ).order_by(Contract.created_at.desc()).all()
            jobs = [contract.job for contract in contracts if contract.job]
            template = 'worker_jobs.html'
        return render_template(template, jobs=jobs)
    except Exception as e:
        app.logger.error(f"Error in my_jobs route: {str(e)}")
        # Fallback to dashboard if there's an error
        flash('Unable to load jobs. Please try again.', 'error')
        return redirect(url_for('dashboard'))
'''
    # 2. Create the earnings route fix
    earnings_route_code = '''
# Add this to app/routes.py after the my-jobs route
@app.route('/earnings')
@login_required
def earnings():
    """Redirect to worker analytics"""
    return redirect(url_for('analytics_worker'))
'''
    # 3. Fix for logout redirect
    logout_fix = '''
# In app/routes.py, find the logout route (around line 468) and change:
# FROM: window.location.href = '/';
# TO:   window.location.href = '/login';
'''
    # 4. Fix for profile route
    profile_fix = '''
# In app/routes.py, update the profile route (around line 710) to handle missing models:
@app.route('/profile')
@login_required
def profile():
    """Display user profile with safe model checking"""
    try:
        # Initialize default values
        recent_contracts = []
        recent_jobs = []
        # Only query if models exist
        try:
            from app.models.contract import Contract
            from app.models.job import Job
            if current_user.role == 'worker':
                recent_contracts = Contract.query.filter_by(
                    worker_id=current_user.id
                ).order_by(Contract.created_at.desc()).limit(5).all()
            elif current_user.role == 'employer':
                recent_jobs = Job.query.filter_by(
                    employer_id=current_user.id
                ).order_by(Job.created_at.desc()).limit(5).all()
        except ImportError:
            # Models don't exist yet, that's okay
            pass
        except Exception as e:
            app.logger.warning(f"Could not load profile data: {str(e)}")
        return render_template('profile.html',
                             user=current_user,
                             recent_contracts=recent_contracts,
                             recent_jobs=recent_jobs)
    except Exception as e:
        app.logger.error(f"Error in profile route: {str(e)}")
        flash('Unable to load profile. Please try again.', 'error')
        return redirect(url_for('dashboard'))
'''
    print("=" * 70)
    print("DASHBOARD NAVIGATION FIXES")
    print("=" * 70)
    print("\n1. MY JOBS ROUTE FIX:")
    print(my_jobs_route_code)
    print("\n2. EARNINGS ROUTE FIX:")
    print(earnings_route_code)
    print("\n3. LOGOUT REDIRECT FIX:")
    print(logout_fix)
    print("\n4. PROFILE ROUTE FIX:")
    print(profile_fix)
    # Create templates for my-jobs if they don't exist
    employer_jobs_template = '''
<!-- app/templates/employer_jobs.html -->
{% extends "base.html" %}
{% block content %}
<div class="container mt-4">
    <h2>My Posted Jobs</h2>
    {% if jobs %}
    <div class="row">
        {% for job in jobs %}
        <div class="col-md-6 mb-3">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{{ job.title }}</h5>
                    <p class="card-text">{{ job.description[:100] }}...</p>
                    <p class="text-muted">Posted: {{ job.created_at.strftime('%Y-%m-%d') }}</p>
                    <a href="/job/{{ job.id }}" class="btn btn-primary">View Details</a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <p>You haven't posted any jobs yet.</p>
    <a href="/create-job" class="btn btn-primary">Post a Job</a>
    {% endif %}
</div>
{% endblock %}
'''
    worker_jobs_template = '''
<!-- app/templates/worker_jobs.html -->
{% extends "base.html" %}
{% block content %}
<div class="container mt-4">
    <h2>My Active Jobs</h2>
    {% if jobs %}
    <div class="row">
        {% for job in jobs %}
        <div class="col-md-6 mb-3">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{{ job.title }}</h5>
                    <p class="card-text">{{ job.description[:100] }}...</p>
                    <p class="text-muted">Started: {{ job.created_at.strftime('%Y-%m-%d') }}</p>
                    <a href="/job/{{ job.id }}" class="btn btn-primary">View Details</a>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <p>You don't have any active jobs.</p>
    <a href="/marketplace" class="btn btn-primary">Browse Jobs</a>
    {% endif %}
</div>
{% endblock %}
'''
    print("\n5. TEMPLATE FILES TO CREATE:")
    print("\nemployer_jobs.html:")
    print(employer_jobs_template)
    print("\nworker_jobs.html:")
    print(worker_jobs_template)
    return True
if __name__ == "__main__":
    create_navigation_fixes()
