<?php

namespace App\Services\Probes;

use App\Models\AgentProbe;
use App\Models\Ticket;

/**
 * Surfaces recent probe results for a ticket as a prompt block. Designed
 * for ADMIN NOTES ONLY by default — raw probe output goes to the
 * `result_text` column; we expose `result_summary` (1-2 line synopsis)
 * to the AI to keep customer-facing replies from quoting raw paths /
 * IPs / hostnames.
 *
 * The drafter calls this only for AdminNoteAssist; HumanizedReplyDrafter
 * (customer-facing) does NOT include this block by default, since the
 * customer-visible reply should be derived from the summary only and
 * the existing Phase-1 context already exposes the aggregate signals.
 */
class ProbeResultsContext
{
    /** Probes older than this aren't relevant context. */
    public const FRESHNESS_HOURS = 24;

    public function buildPromptBlock(Ticket $ticket): string
    {
        $probes = AgentProbe::where('ticket_id', $ticket->id)
            ->where('created_at', '>=', now()->subHours(self::FRESHNESS_HOURS))
            ->orderBy('id')
            ->get(['id', 'probe_type', 'status', 'result_summary',
                   'exit_code', 'completed_at', 'queued_at', 'params']);

        if ($probes->isEmpty()) return '';

        $lines = ["## On-demand probes run for this ticket (read-only checks via the agent)"];
        $lines[] = "Each probe is a fixed, allow-listed check; the AI / operator never types free-form shell. Use these results to ground your note; if a probe is still pending, mention that — don't claim its expected verdict.";
        foreach ($probes as $p) {
            $when = $p->completed_at?->diffForHumans() ?: 'queued ' . $p->queued_at?->diffForHumans();
            $tag  = match ($p->status) {
                AgentProbe::STATUS_SUCCESS  => '✓',
                AgentProbe::STATUS_FAILED   => '✗',
                AgentProbe::STATUS_PENDING  => '⌛ pending',
                AgentProbe::STATUS_RUNNING  => '⌛ running',
                AgentProbe::STATUS_EXPIRED  => '⏱ expired',
                default                     => '?',
            };
            $paramStr = ! empty($p->params)
                ? ' (' . implode(', ', array_map(fn ($k, $v) => "{$k}={$v}",
                                                  array_keys($p->params),
                                                  array_values($p->params))) . ')'
                : '';
            $summary = $p->result_summary
                ?: ($p->status === AgentProbe::STATUS_PENDING || $p->status === AgentProbe::STATUS_RUNNING
                    ? 'awaiting result'
                    : '(no summary)');
            $lines[] = "  · {$tag} {$p->probe_type}{$paramStr} — {$summary} [{$when}]";
        }
        return implode("\n", $lines);
    }
}
