<?php
namespace boru\ai\Runtime;

class ToolContext
{
    /** @var array */
    protected $data = array();

    public function __construct(array $data = array())
    {
        $this->data = $data;
    }

    public function set($key, $value)
    {
        $segments = explode('.', (string)$key);
        $target = &$this->data;

        foreach ($segments as $segment) {
            if (!isset($target[$segment]) || !is_array($target[$segment])) {
                $target[$segment] = array();
            }
            $target = &$target[$segment];
        }

        $target = $value;
        return $this;
    }

    public function get($key = null, $default = null)
    {
        if ($key === null) {
            return $this->data;
        }

        $segments = explode('.', (string)$key);
        $target = $this->data;

        foreach ($segments as $segment) {
            if (!is_array($target) || !array_key_exists($segment, $target)) {
                return $default;
            }
            $target = $target[$segment];
        }

        return $target;
    }

    public function all()
    {
        return $this->data;
    }
}
