#!/usr/bin/env python3
"""
Add missing /workers and /api/workers routes to fix 500 errors
"""

import sys
import os
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

print("Adding missing /workers and /api/workers routes...")
print("=" * 60)

routes_path = "app/routes.py"

# Read the current routes file
with open(routes_path, 'r', encoding='utf-8') as f:
    content = f.read()

# Check if routes already exist
has_workers = '@app.route("/workers")' in content or '@bp.route("/workers")' in content
has_api_workers = '@app.route("/api/workers")' in content or '@bp.route("/api/workers")' in content

if not has_workers or not has_api_workers:
    print(f"Adding missing routes to {routes_path}")
    
    # Find a good place to insert the routes (after imports)
    lines = content.split('\n')
    
    # Find the last import line
    insert_idx = 0
    for i, line in enumerate(lines):
        if line.startswith('from ') or line.startswith('import '):
            insert_idx = i + 1
    
    # Skip any blank lines after imports
    while insert_idx < len(lines) and lines[insert_idx].strip() == '':
        insert_idx += 1
    
    # Add the routes
    new_routes = []
    
    if not has_workers:
        new_routes.extend([
            '',
            '@app.route("/workers")',
            'def workers():',
            '    """List workers page"""',
            '    from app.models.user import User',
            '    workers = User.query.filter_by(user_type="worker").all()',
            '    return render_template("workers/list.html", workers=workers)',
        ])
        print("   ✓ Added /workers route")
    
    if not has_api_workers:
        new_routes.extend([
            '',
            '@app.route("/api/workers")',
            'def api_workers():',
            '    """API endpoint to get workers list"""',
            '    from app.models.user import User',
            '    workers = User.query.filter_by(user_type="worker").all()',
            '    workers_data = [',
            '        {',
            '            "id": w.id,',
            '            "username": w.username,',
            '            "email": w.email,',
            '            "created_at": w.created_at.isoformat() if w.created_at else None',
            '        }',
            '        for w in workers',
            '    ]',
            '    return jsonify(workers_data)',
        ])
        print("   ✓ Added /api/workers route")
    
    # Insert the new routes
    for route_line in reversed(new_routes):
        lines.insert(insert_idx, route_line)
    
    # Make sure jsonify is imported
    if 'from flask import' in content and 'jsonify' not in content:
        for i, line in enumerate(lines):
            if line.startswith('from flask import'):
                if not line.endswith(','):
                    lines[i] = line + ', jsonify'
                else:
                    lines[i] = line + ' jsonify'
                print("   ✓ Added jsonify import")
                break
    
    # Write the updated content
    with open(routes_path, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))
    
    print("   ✓ Routes added successfully")
else:
    print("   ✓ Routes already exist")

# Create a basic workers list template if it doesn't exist
template_dir = "app/templates/workers"
template_path = os.path.join(template_dir, "list.html")

if not os.path.exists(template_dir):
    os.makedirs(template_dir)
    print(f"   ✓ Created {template_dir} directory")

if not os.path.exists(template_path):
    template_content = '''{% extends "base.html" %}

{% block title %}Workers - RateRight{% endblock %}

{% block content %}
<div class="container mt-4">
    <h1>Workers</h1>
    
    <div class="row mt-4">
        {% for worker in workers %}
        <div class="col-md-4 mb-3">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">{{ worker.username }}</h5>
                    <p class="card-text">{{ worker.email }}</p>
                    <a href="#" class="btn btn-primary">View Profile</a>
                </div>
            </div>
        </div>
        {% else %}
        <div class="col-12">
            <p>No workers found.</p>
        </div>
        {% endfor %}
    </div>
</div>
{% endblock %}
'''
    
    with open(template_path, 'w', encoding='utf-8') as f:
        f.write(template_content)
    print(f"   ✓ Created {template_path}")
else:
    print(f"   ✓ Template {template_path} already exists")

print("\n" + "=" * 60)
print("Routes and templates added successfully!")
