<?php

namespace App\Synapse\Agents;

use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Ai\Attributes\MaxTokens;
use Laravel\Ai\Attributes\Model;
use Laravel\Ai\Attributes\Provider;
use Laravel\Ai\Attributes\Timeout;
use Laravel\Ai\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;
use Stringable;

#[Provider('openai')]
#[Model('gpt-4o')]
#[MaxTokens(1000)]
#[Timeout(60)]
class DocumentDataExtractorAgent implements Agent, HasStructuredOutput
{
    use Promptable;

    public function instructions(): Stringable|string
    {
        return <<<'SYSTEM'
You are Synapse, a document data extraction specialist for a legal claims management firm.

You will receive a document image or PDF. Extract every data field you can read.

For each field:
- Return the exact value as it appears on the document (do not reformat dates, names, or references).
- Return null if the field is not present or not legible.
- For signature_present and photograph_present, return true only if you can clearly see them.

Detect the document type from visual appearance (e.g. "UK Passport", "UK Driving Licence", "Utility Bill", "Bank Statement", "NHS Letter", "Birth Certificate").

Rate your overall extraction confidence:
- high: most fields clearly legible, document in good condition
- medium: some fields partially legible or uncertain
- low: document quality poor, many fields unreadable

Rules:
- Extract only what is visible. Do not infer or guess values.
- If you cannot read the document at all, return null for all fields and confidence "low".
SYSTEM;
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'document_type'      => $schema->string()->required(),
            'full_name'          => $schema->string()->nullable()->required(),
            'date_of_birth'      => $schema->string()->nullable()->required(),
            'issue_date'         => $schema->string()->nullable()->required(),
            'expiry_date'        => $schema->string()->nullable()->required(),
            'address'            => $schema->string()->nullable()->required(),
            'document_reference' => $schema->string()->nullable()->required(),
            'issuing_authority'  => $schema->string()->nullable()->required(),
            'signature_present'  => $schema->boolean()->required(),
            'photograph_present' => $schema->boolean()->required(),
            'confidence'         => $schema->string()->required(),
        ];
    }
}
