<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\BaseModel;

final class TrainingExampleModel extends BaseModel
{
    protected string $table = 'training_examples';
    protected array $fillable = ['feature', 'prompt_text', 'ideal_response', 'notes'];
    protected bool $timestamps = false;
    protected bool $softDeletes = false;
    protected bool $auditStamps = false;

    public function forFeature(string $feature): array
    {
        $stmt = $this->db->prepare(
            "SELECT te.*, CONCAT(u.first_name, ' ', u.last_name) AS created_by_name
             FROM training_examples te
             LEFT JOIN users u ON u.id = te.created_by
             WHERE te.feature = :feature ORDER BY te.created_at DESC"
        );
        $stmt->execute(['feature' => $feature]);

        return $stmt->fetchAll();
    }

    public function create(string $feature, string $prompt, string $idealResponse, ?string $notes, int $userId): int
    {
        $stmt = $this->db->prepare(
            'INSERT INTO training_examples (feature, prompt_text, ideal_response, notes, created_by, created_at)
             VALUES (:feature, :prompt, :response, :notes, :user, NOW())'
        );
        $stmt->execute(['feature' => $feature, 'prompt' => $prompt, 'response' => $idealResponse, 'notes' => $notes, 'user' => $userId]);

        return (int) $this->db->lastInsertId();
    }

    /** JSONL export (one JSON object per line) — the standard format for fine-tuning datasets. */
    public function exportJsonl(string $feature): string
    {
        $rows = $this->forFeature($feature);
        $lines = [];

        foreach ($rows as $row) {
            $lines[] = json_encode([
                'messages' => [
                    ['role' => 'user', 'content' => $row['prompt_text']],
                    ['role' => 'assistant', 'content' => $row['ideal_response']],
                ],
            ]);
        }

        return implode("\n", $lines);
    }
}
