<?php
namespace Nibiru\Module\Ai\Plugins\Tools;

use Nibiru\Module\Ai\Plugins\Tool;

/**
 * Read a project file by path (relative to the application root). Lets
 * the agent quote real source when answering "where is X defined?" type
 * questions. Read-only. No path-traversal — `..` is blocked.
 */
class FileRead extends Tool
{
    public function name(): string { return 'file_read'; }

    public function description(): string
    {
        return 'Read a file from the project. Path is relative to the application root '
             . '(the directory containing index.php). Returns up to 8 KB.';
    }

    public function schema(): array
    {
        return [
            'path' => [
                'type' => 'string',
                'description' => 'Relative path, e.g. "application/controller/loginController.php".',
                'required' => true,
            ],
        ];
    }

    public function execute(array $args): mixed
    {
        $path = (string) ($args['path'] ?? '');
        if ($path === '' || str_contains($path, '..')) {
            return 'ERROR: invalid path';
        }
        // Application root = three levels up from this plugin file:
        //   application/module/ai/plugins/tools/fileRead.php
        //   ↑       ↑      ↑    ↑       ↑      ↑
        //   app    module  ai   plugins tools  this
        $root = realpath(__DIR__ . '/../../../../../');
        if ($root === false) return 'ERROR: cannot resolve app root';
        $abs = realpath($root . DIRECTORY_SEPARATOR . $path);
        if ($abs === false || !is_file($abs)) return 'ERROR: file not found';
        if (strpos($abs, $root) !== 0) return 'ERROR: path escapes root';
        $body = (string) file_get_contents($abs);
        if (strlen($body) > 8192) $body = substr($body, 0, 8192) . "\n…[truncated]";
        return $body;
    }
}
