<?php

/**
 * LolaCore — SafetyConfig
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore\Chat;

use LolaCore\Admin\Settings;

/**
 * Data Transfer Object for Safety Configuration used to modulate
 * the LLM system prompt and SOPs.
 */
class SafetyConfig
{
    /**
     * Whether to require confirmation for write actions.
     *
     * @var bool
     */
    public bool $confirmWrites;

    /**
     * Whether to require backups for destructive actions.
     *
     * @var bool
     */
    public bool $requireBackup;

    /**
     * Whether to explain step by step before showing an action preview.
     *
     * @var bool
     */
    public bool $learningMode;

    /**
     * Factory method to create an instance from database configuration.
     *
     * @return self
     */
    public static function fromDatabase(): self
    {
        $cfg = new self();
        $cfg->confirmWrites = self::parseBoolConfig('safety_confirm_writes', true);
        $cfg->requireBackup = self::parseBoolConfig('safety_require_backup', false);
        $cfg->learningMode  = self::parseBoolConfig('safety_learning_mode', false);

        return $cfg;
    }

    /**
     * Strict boolean parser for config values. The DB stores all config as strings,
     * and a naive `(bool)` cast misinterprets values like 'false' (truthy non-empty
     * string) or '' (silently overrides default). This whitelists the canonical
     * truthy representations we accept.
     */
    private static function parseBoolConfig(string $key, bool $default): bool
    {
        $value = Settings::getConfig($key, $default ? '1' : '0');
        return in_array($value, ['1', 1, 'true', true], true);
    }
}
