<?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\Contracts\Agent;
use Laravel\Ai\Contracts\HasStructuredOutput;
use Laravel\Ai\Promptable;
use Stringable;

#[Provider('openai')]
#[Model('gpt-4o-mini')]
#[MaxTokens(150)]
class ExtractDsarReferenceAgent implements Agent, HasStructuredOutput
{
    use Promptable;

    public function instructions(): Stringable|string
    {
        return <<<'SYSTEM'
You are a reference number extractor. You will be given an inbound email from a healthcare institution responding to a Data Subject Access Request (DSAR) sent by a firm of solicitors.

Your task is to extract the INSTITUTION'S OWN reference number (field: reference).
The firm's own reference (DSAR-YYYYMMDD-XXXXXX format) is handled separately upstream — do NOT return it as the institution reference.

INSTITUTION REFERENCE (field: reference)
The reference number the institution has assigned to this case internally.
Look for:
- "Our reference: IGO-2024-1234"
- "Our ref / Case ref: FOI/2024/056"
- "Case number: CAS-98765"
- "Reference: SAR/2024/00123"
- "Request ID: REQ-20240501"
- "The request has been given the unique reference number [X]"
- Any alphanumeric code clearly labelled as the institution's own reference

IMPORTANT — scan the ENTIRE email, including:
- All quoted/replied thread content (lines prefixed with >, forwarded blocks, "On [date] [someone] wrote:" sections)
- Any ATTACHMENT sections (labelled "--- ATTACHMENT: filename ---" in this prompt)
If the institution reference is not in the email body, check the attachment sections before returning null.

OUR REFERENCE (field: our_reference)
The solicitor firm's own reference quoted back by the institution. This is only needed for context — the primary extraction target is the institution reference.
Look for:
- "Your reference: [X]", "Your ref: [X]"
- "Re: [X]" where X looks like a case reference code

Return null for either field if no clear reference exists.
Do not return NHS numbers, dates of birth, or codes you are not confident are references.
SYSTEM;
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'reference' => $schema
                ->string()
                ->nullable()
                ->description("The institution's own reference/case number for this DSAR, or null if not found")
                ->required(),
            'our_reference' => $schema
                ->string()
                ->nullable()
                ->description("The solicitor firm's own reference quoted back by the institution, or null if not found")
                ->required(),
            'confidence' => $schema
                ->string()
                ->description('high | medium | low — confidence for the institution reference')
                ->required(),
        ];
    }
}
