<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ApiProvider;
use App\Api\Plugins\PluginLoader;
use Illuminate\Http\Request;

class AiStatusController extends Controller
{
    public function checkStatus(Request $request)
    {
        $providers = ApiProvider::where('enabled', true)->get();
        $results = [];

        foreach ($providers as $provider) {
            try {
                $plugin = PluginLoader::getPlugin($provider->plugin, $provider);
                $status = $plugin->checkAvailability();
                $results[] = $status;
            } catch (\Exception $e) {
                $results[] = [
                    'available' => false,
                    'reason' => 'Plugin error: ' . $e->getMessage(),
                    'provider_id' => $provider->id,
                    'provider_name' => $provider->name
                ];
            }
        }

        return response()->json($results);
    }

    public function checkAndUpdateStatus(Request $request)
    {
        $providers = ApiProvider::all();
        $anyAvailable = false;

        foreach ($providers as $provider) {
            try {
                $plugin = PluginLoader::getPlugin($provider->plugin, $provider);
                $status = $plugin->checkAvailability();

                if (!$status['available']) {
                    // Deaktiviere den Provider, wenn nicht verfügbar
                    $provider->enabled = false;
                    $provider->save();
        
                    // Deaktiviere alle zugehörigen Modelle
                    foreach ($provider->aiModels as $model) {
                        $model->enabled = false;
                        $model->save();
        
                        // Deaktiviere alle zugehörigen Styles
                        foreach ($model->styles as $style) {
                            $style->enabled = false;
                            $style->save();
                        }
                    }
                } else {
                    $anyAvailable = true;
                    // Stelle sicher, dass der Provider aktiviert ist, wenn er verfügbar ist
                    $provider->enabled = true;
                    $provider->save();
                }
            } catch (\Exception $e) {
                $provider->enabled = false;
                $provider->save();
            }
        }

        return response()->json([
            'success' => true,
            'any_available' => $anyAvailable,
            'message' => 'AI status check and update completed'
        ]);
    }
}