<?php

declare(strict_types=1);

namespace Activetwist\Jsonm\Util;

use RuntimeException;

/**
 * Pure dotted-path access for nested associative arrays. Carries no JSONM
 * semantics — semantic-token and derived-token resolution live in
 * Activetwist\Jsonm\Validator.
 */
final class PathAccess
{
    public static function get(array $data, string $path): mixed
    {
        $segments = explode('.', $path);
        $current = $data;
        foreach ($segments as $segment) {
            if (!is_array($current) || !array_key_exists($segment, $current)) {
                throw new RuntimeException("Path not found: {$path}");
            }
            $current = $current[$segment];
        }
        return $current;
    }

    public static function exists(array $data, string $path): bool
    {
        $segments = explode('.', $path);
        $current = $data;
        foreach ($segments as $segment) {
            if (!is_array($current) || !array_key_exists($segment, $current)) {
                return false;
            }
            $current = $current[$segment];
        }
        return true;
    }

    public static function set(array &$data, string $path, mixed $value): void
    {
        $segments = explode('.', $path);
        $current = &$data;
        foreach ($segments as $segment) {
            if (!isset($current[$segment]) || !is_array($current[$segment])) {
                $current[$segment] = [];
            }
            $current = &$current[$segment];
        }
        $current = $value;
    }
}
