<?php

namespace App\Synapse\Context;

use App\Models\Claim\Claim;

/**
 * Renders a claim's care settings as a compact candidate list for the
 * CareSettingTaggerAgent to match extracted evidence quotes against.
 * Only settings with a linked institution are included (the id is what the
 * agent returns).
 */
class CareSettingsContext
{
    public static function fromClaim(Claim $claim): string
    {
        $claim->loadMissing(['careSettings.institution.aliases', 'careSettings.area.council']);

        $settings = $claim->careSettings->filter(fn ($cs) => $cs->institution !== null);

        if ($settings->isEmpty()) {
            return 'No care settings recorded.';
        }

        $lines = ['CARE SETTINGS (candidate placements — match evidence to one of these by id):'];

        foreach ($settings as $cs) {
            $inst    = $cs->institution;
            $aliases = $inst->aliases->pluck('alias')->filter()->join(', ');

            $line = "- id={$cs->id} | " . $inst->display_name;
            if ($aliases) {
                $line .= ' (aka: ' . $aliases . ')';
            }
            if ($cs->localAuthority()) {
                $line .= ' | local authority: ' . $cs->localAuthority();
            }
            $line .= ' | dates: ' . ($cs->dates ?: 'not recorded');
            if ($cs->people_involved) {
                $line .= ' | people: ' . $cs->people_involved;
            }

            $lines[] = $line;
        }

        return implode("\n", $lines);
    }
}
