<?php

namespace App\Mcp\Tools\Agent;

use App\Domain\Agent\Actions\ExportAgentWorkspaceAction;
use App\Domain\Agent\Models\Agent;
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\IsReadOnly;

#[IsReadOnly]
#[AssistantTool('read')]
class AgentWorkspaceExportTool extends Tool
{
    use HasStructuredErrors;

    protected string $name = 'agent_workspace_export';

    protected string $description = 'Export an agent\'s full workspace — identity & definition (role, goal, backstory, model, reasoning strategy, capabilities, constraints, output schema), tools, skills, memories, and soul.md — as a zip or yaml file for GitOps/portability. Round-trips via agent_workspace_import. Returns the file path for download.';

    public function schema(JsonSchema $schema): array
    {
        return [
            'agent_id' => $schema->string()
                ->description('The agent UUID to export')
                ->required(),
            'format' => $schema->string()
                ->description('Export format: zip or yaml (default: zip)')
                ->enum(['zip', 'yaml'])
                ->default('zip'),
            'include_memories' => $schema->boolean()
                ->description('Whether to include agent memories in export (default: true)')
                ->default(true),
        ];
    }

    public function handle(Request $request): Response
    {
        $validated = $request->validate([
            'agent_id' => 'required|string',
            'format' => 'nullable|string|in:zip,yaml',
            'include_memories' => 'nullable|boolean',
        ]);

        $teamId = (app()->bound('mcp.team_id') ? app('mcp.team_id') : null) ?? auth()->user()?->current_team_id;
        if (! $teamId) {
            return $this->permissionDeniedError('No current team.');
        }

        $agent = Agent::withoutGlobalScopes()->where('team_id', $teamId)->find($validated['agent_id']);
        if (! $agent) {
            return $this->notFoundError('agent');
        }

        try {
            $path = app(ExportAgentWorkspaceAction::class)->execute(
                agent: $agent,
                format: $validated['format'] ?? 'zip',
                includeMemories: $validated['include_memories'] ?? true,
            );

            return Response::text(json_encode([
                'success' => true,
                'agent_id' => $agent->id,
                'agent_name' => $agent->name,
                'format' => $validated['format'] ?? 'zip',
                'file_path' => $path,
                'file_name' => basename($path),
            ]));
        } catch (\Throwable $e) {
            throw $e;
        }
    }
}
