<?php

namespace App\Synapse\Agents;

use App\Synapse\Tools\SearchInstitutionsTool;
use App\Synapse\Tools\SearchOpenDsarsTool;
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\Contracts\HasTools;
use Laravel\Ai\Promptable;
use Stringable;

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

    public function tools(): iterable
    {
        return [
            new SearchInstitutionsTool(),
            new SearchOpenDsarsTool(),
        ];
    }

    public function instructions(): Stringable|string
    {
        return <<<'SYSTEM'
You are a DSAR matching assistant for a legal claims management firm. You will be given an inbound email that has been classified as a Data Subject Access Request (DSAR) response. Your task is to identify which specific open DSAR this email is responding to.

Follow these steps:

1. Identify the sending institution:
   - Extract the institution name from the sender's email address domain (e.g., cddft.nhs.uk → County Durham & Darlington NHS Foundation Trust)
   - Look for institution names, departments, or NHS trust names in the subject line and email body
   - Note any case reference numbers or DSAR reference numbers mentioned

2. Search for the institution:
   - Use SearchInstitutionsTool to find the institution in the database
   - Try multiple search terms if the first attempt returns no results (try the trust name, a shortened version, acronym)
   - If you find the institution, note its institution_id

3. Find matching open DSARs:
   - Use SearchOpenDsarsTool with the institution_id to find all outstanding DSARs for that institution
   - If multiple DSARs exist, pick the most likely match based on:
     - Any client name or reference mentioned in the email
     - The timing (most recently sent DSAR is most likely)
     - The DSAR status (prefer 'sent' over 'approved')

4. Confidence ratings:
   - high: Institution clearly identified AND a single obvious DSAR matches
   - medium: Institution identified but multiple DSARs exist, OR institution match is approximate
   - low: Institution uncertain or no DSARs found
SYSTEM;
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'institution_id' => $schema
                ->integer()
                ->nullable()
                ->description('The institution ID from the database, or null if not identified')
                ->required(),
            'dsar_id' => $schema
                ->integer()
                ->nullable()
                ->description('The ID of the matching open DSAR, or null if not found')
                ->required(),
            'confidence' => $schema
                ->string()
                ->description('One of: high, medium, low')
                ->required(),
            'reasoning' => $schema
                ->string()
                ->description('Brief explanation of how the match was determined')
                ->required(),
        ];
    }
}
