<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Response;
use App\Helpers\AjaxResponse;
use App\Models\TrainingExampleModel;
use App\Services\ActivityLogger;

final class TrainingDataController extends BaseController
{
    public function index(Request $request): Response
    {
        $model = new TrainingExampleModel();
        $examples = [
            'ai_assistant' => $model->forFeature('ai_assistant'),
            'chatbot' => $model->forFeature('chatbot'),
            'voice_agent' => $model->forFeature('voice_agent'),
        ];

        if ($request->isAjax() || $request->isJson()) {
            return AjaxResponse::success($examples);
        }

        return $this->view('ai/training-data', [
            'title' => 'Training Data',
            'activeNav' => 'training-data',
            'breadcrumbs' => [['Home', 'dashboard'], ['AI', 'ai-assistant'], ['Training Data', 'training-data']],
            'examples' => $examples,
        ]);
    }

    public function store(Request $request): Response
    {
        $data = $this->validateOrFail($request, [
            'feature' => 'required|in:ai_assistant,chatbot,voice_agent',
            'prompt_text' => 'required|string',
            'ideal_response' => 'required|string',
            'notes' => 'nullable|string|max:500',
        ]);

        $id = (new TrainingExampleModel())->create(
            $data['feature'], $data['prompt_text'], $data['ideal_response'], $data['notes'] ?? null, $this->currentUserId()
        );
        ActivityLogger::logAction('Training example added', 'admin');

        return AjaxResponse::created(['id' => $id], 'Training example saved.');
    }

    public function destroy(Request $request, array $params): Response
    {
        (new TrainingExampleModel())->delete((int) $params['id']);

        return AjaxResponse::success(null, 'Training example deleted.');
    }

    public function export(Request $request, array $params): Response
    {
        $feature = $params['feature'];
        $jsonl = (new TrainingExampleModel())->exportJsonl($feature);

        return Response::html($jsonl)
            ->withHeader('Content-Type', 'application/jsonl; charset=UTF-8')
            ->withHeader('Content-Disposition', "attachment; filename=\"{$feature}-training-data.jsonl\"");
    }
}
