<?php

namespace App\Mcp\Tools\Evolution;

use App\Domain\Agent\Models\Agent;
use App\Domain\Agent\Models\AgentExecution;
use App\Domain\Evolution\Actions\AnalyzeExecutionForEvolutionAction;
use App\Mcp\Attributes\AssistantTool;
use App\Mcp\Concerns\HasStructuredErrors;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;

#[IsDestructive]
#[AssistantTool('write')]
class EvolutionAnalyzeTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'evolution_analyze';

    protected string $description = 'Analyze an agent\'s performance and generate an evolution proposal with suggested improvements.';

    public function schema(JsonSchema $schema): array
    {
        return [
            'agent_id' => $schema->string()
                ->description('The agent ID to analyze')
                ->required(),
        ];
    }

    public function handle(Request $request): Response
    {
        $teamId = app('mcp.team_id') ?? auth()->user()?->current_team_id;
        if (! $teamId) {
            return $this->permissionDeniedError('No current team.');
        }
        $agent = Agent::withoutGlobalScopes()->where('team_id', $teamId)->findOrFail($request->get('agent_id'));
        /** @var AgentExecution|null $latestExecution */
        $latestExecution = $agent->executions()->latest()->first();

        $proposal = app(AnalyzeExecutionForEvolutionAction::class)->execute(
            $agent,
            $latestExecution,
        );

        return Response::text(json_encode([
            'id' => $proposal->id,
            'status' => $proposal->status->value,
            'analysis' => $proposal->analysis,
            'proposed_changes' => $proposal->proposed_changes,
            'reasoning' => $proposal->reasoning,
            'confidence_score' => $proposal->confidence_score,
        ]));
    }
}
