<?php

declare(strict_types=1);

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AiProvider;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class AdminAiProviderController extends Controller
{
    public function index(): View
    {
        $providers = AiProvider::orderByDesc('is_default')
            ->orderBy('name')
            ->get();

        return view('admin.ai-providers.index', compact('providers'));
    }

    public function create(): View
    {
        return view('admin.ai-providers.create');
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|unique:ai_providers,code|alpha_dash',
            'api_key' => 'nullable|string|max:500',
            'api_url' => 'nullable|string|max:500',
            'model' => 'nullable|string|max:100',
            'is_enabled' => 'boolean',
            'is_default' => 'boolean',
            'capabilities' => 'nullable|array',
            'capabilities.*' => 'string|in:chat,vision,reasoning,tools,streaming',
            'max_tokens' => 'nullable|integer|min:1|max:32000',
            'temperature' => 'nullable|decimal:0,2|min:0|max:2',
            'max_steps' => 'nullable|integer|min:1|max:20',
        ]);

        if (empty($validated['api_url'])) {
            $validated['api_url'] = $this->getDefaultUrlForCode($validated['code']);
        }

        $provider = AiProvider::create($validated);

        if ($provider->is_default) {
            $provider->setAsDefault();
        }

        return redirect()->route('admin.ai-providers.index')
            ->with('success', "AI provider '{$provider->name}' created successfully.");
    }

    public function edit(AiProvider $ai_provider): View
    {
        return view('admin.ai-providers.edit', compact('ai_provider'));
    }

    public function update(Request $request, AiProvider $ai_provider): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'code' => 'required|string|max:50|alpha_dash|unique:ai_providers,code,'.$ai_provider->id,
            'api_key' => 'nullable|string|max:500',
            'api_url' => 'nullable|string|max:500',
            'model' => 'nullable|string|max:100',
            'is_enabled' => 'boolean',
            'is_default' => 'boolean',
            'capabilities' => 'nullable|array',
            'capabilities.*' => 'string|in:chat,vision,reasoning,tools,streaming',
            'max_tokens' => 'nullable|integer|min:1|max:32000',
            'temperature' => 'nullable|decimal:0,2|min:0|max:2',
            'max_steps' => 'nullable|integer|min:1|max:20',
        ]);

        // If API key is empty and wasn't changed, keep the existing one
        if (empty($validated['api_key']) && $request->input('api_key_changed') === '0') {
            $validated['api_key'] = $ai_provider->api_key;
        }

        // Only update API key if explicitly provided
        if ($request->input('api_key_changed') === '1' && empty($validated['api_key'])) {
            $validated['api_key'] = null;
        }

        $ai_provider->fill($validated);
        $ai_provider->save();

        if ($ai_provider->is_default) {
            $ai_provider->setAsDefault();
        }

        return redirect()->route('admin.ai-providers.index')
            ->with('success', "AI provider '{$ai_provider->name}' updated successfully.");
    }

    public function destroy(AiProvider $ai_provider): RedirectResponse
    {
        $name = $ai_provider->name;
        $ai_provider->delete();

        return redirect()->route('admin.ai-providers.index')
            ->with('success', "AI provider '{$name}' deleted successfully.");
    }

    public function setDefault(AiProvider $ai_provider): RedirectResponse
    {
        $ai_provider->setAsDefault();

        return back()->with('success', "AI provider '{$ai_provider->name}' set as default.");
    }

    public function toggle(AiProvider $ai_provider): RedirectResponse
    {
        $ai_provider->update(['is_enabled' => ! $ai_provider->is_enabled]);

        $status = $ai_provider->is_enabled ? 'enabled' : 'disabled';

        return back()->with('success', "AI provider '{$ai_provider->name}' {$status}.");
    }

    protected function getDefaultUrlForCode(string $code): ?string
    {
        return match ($code) {
            'openai' => 'https://api.openai.com/v1',
            'anthropic' => 'https://api.anthropic.com/v1',
            'gemini' => 'https://generativelanguage.googleapis.com/v1beta/models',
            'deepseek' => 'https://api.deepseek.com/v1',
            'mistral' => 'https://api.mistral.ai/v1',
            'xai' => 'https://api.x.ai/v1',
            'groq' => 'https://api.groq.com/openai/v1',
            'ollama' => 'http://localhost:11434/v1',
            default => null,
        };
    }
}
