<?php

namespace App\Components\Synapse;

use App\Models\Document\Document;
use App\Models\Solicitor\Solicitor;
use App\Models\Synapse\SynapseRun;
use App\Synapse\Agents\DocumentReviewerAgent;
use Laravel\Ai\Files;
use Livewire\Component;

class DocumentReviewer extends Component
{
    public Document $document;
    public string   $storagePath;
    public string   $storageDisk = 'public';

    public bool    $open    = false;
    public bool    $running = false;
    public bool    $ran     = false;
    public ?string $error   = null;

    public function open(): void  { $this->open = true; }
    public function close(): void { $this->open = false; }

    public function mount(Document $document, string $storagePath, string $storageDisk = 'public'): void
    {
        $this->document    = $document;
        $this->storagePath = $storagePath;
        $this->storageDisk = $storageDisk;
    }

    public function review(): void
    {
        abort_if(!auth()->user()->can('synapse.use'), 403);

        $this->error   = null;
        $this->running = true;
        $this->ran     = false;

        try {
            $attachment = $this->resolveAttachment();

            $prompt = "Please review the attached document and produce a quality assessment report.\n\n"
                . "Document name: " . $this->document->display_name . "\n"
                . "Document type: " . ($this->document->type?->display_name ?? 'Unknown') . "\n"
                . "File type: " . $this->document->file_type;

            $stream = (new DocumentReviewerAgent)->stream($prompt, attachments: [$attachment]);

            foreach ($stream as $event) {
                if (!empty($event->text)) {
                    $this->stream(to: 'synapseOutput', content: $event->text);
                }
            }

            $this->ran     = true;
            $this->running = false;

            $this->recordRun();

        } catch (\Throwable $e) {
            $this->error   = 'Synapse encountered an error: ' . $e->getMessage();
            $this->running = false;
            report($e);
        }
    }

    protected function resolveAttachment(): Files\Image|Files\Document
    {
        if ($this->document->file_type === 'application/pdf') {
            return Files\Document::fromStorage($this->storagePath, disk: $this->storageDisk);
        }

        return Files\Image::fromStorage($this->storagePath, disk: $this->storageDisk);
    }

    protected function recordRun(): void
    {
        if (!config('synapse.record_runs', true)) {
            return;
        }

        SynapseRun::create([
            'solicitor_id' => app(Solicitor::class)?->id,
            'user_id'      => auth()->id(),
            'agent_type'   => 'document_reviewer',
            'subject_type' => Document::class,
            'subject_id'   => $this->document->id,
            'status'       => 'completed',
        ]);
    }

    public function render(): \Illuminate\View\View
    {
        return view('components.synapse.document-reviewer');
    }
}
