from microdot import Microdot
from microdot.session import with_session
from models.profile import Profile
import json

controller = Microdot()
profiles = Profile()

@controller.get('')
@with_session
async def list_profiles(request, session):
    """List all profiles with current profile info."""
    profile_list = profiles.list()
    current_id = session.get('current_profile')
    
    # If no current profile in session, use first one
    if not current_id and profile_list:
        current_id = profile_list[0]
        session['current_profile'] = str(current_id)
        session.save()
    
    # Build profiles object
    profiles_data = {}
    for profile_id in profile_list:
        profile_data = profiles.read(profile_id)
        if profile_data:
            profiles_data[profile_id] = profile_data
    
    return json.dumps({
        "profiles": profiles_data,
        "current_profile_id": current_id
    }), 200, {'Content-Type': 'application/json'}

@controller.get('/current')
@with_session
async def get_current_profile(request, session):
    """Get the current profile ID from session (or fallback)."""
    profile_list = profiles.list()
    current_id = session.get('current_profile')
    if not current_id and profile_list:
        current_id = profile_list[0]
        session['current_profile'] = str(current_id)
        session.save()
    if current_id:
        profile = profiles.read(current_id)
        return json.dumps({"id": current_id, "profile": profile}), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "No profile available"}), 404

@controller.get('/<id>')
@with_session
async def get_profile(request, id, session):
    """Get a specific profile by ID."""
    # Handle 'current' as a special case
    if id == 'current':
        return await get_current_profile(request, session)
    
    profile = profiles.read(id)
    if profile:
        return json.dumps(profile), 200, {'Content-Type': 'application/json'}
    return json.dumps({"error": "Profile not found"}), 404

@controller.post('/<id>/apply')
@with_session
async def apply_profile(request, session, id):
    """Apply a profile by saving it to session."""
    if not profiles.read(id):
        return json.dumps({"error": "Profile not found"}), 404
    session['current_profile'] = str(id)
    session.save()
    return json.dumps({"message": "Profile applied", "id": str(id)}), 200, {'Content-Type': 'application/json'}

@controller.post('')
async def create_profile(request):
    """Create a new profile."""
    try:
        data = request.json or {}
        name = data.get("name", "")
        profile_id = profiles.create(name)
        if data:
            profiles.update(profile_id, data)
        profile_data = profiles.read(profile_id)
        return json.dumps({profile_id: profile_data}), 201, {'Content-Type': 'application/json'}
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/current')
@with_session
async def update_current_profile(request, session):
    """Update the current profile using session (or fallback)."""
    try:
        data = request.json or {}
        profile_list = profiles.list()
        current_id = session.get('current_profile')
        if not current_id and profile_list:
            current_id = profile_list[0]
            session['current_profile'] = str(current_id)
            session.save()
        if not current_id:
            return json.dumps({"error": "No profile available"}), 404
        if profiles.update(current_id, data):
            return json.dumps(profiles.read(current_id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Profile not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.put('/<id>')
async def update_profile(request, id):
    """Update an existing profile."""
    try:
        data = request.json
        if profiles.update(id, data):
            return json.dumps(profiles.read(id)), 200, {'Content-Type': 'application/json'}
        return json.dumps({"error": "Profile not found"}), 404
    except Exception as e:
        return json.dumps({"error": str(e)}), 400

@controller.delete('/<id>')
async def delete_profile(request, id):
    """Delete a profile."""
    if profiles.delete(id):
        return json.dumps({"message": "Profile deleted successfully"}), 200
    return json.dumps({"error": "Profile not found"}), 404
