function setDownholeApiKey(apiKey, baseUrl)
%SETDOWNHOLEAPIKEY  Configure Wellbore Genius credentials for this MATLAB session.
%
%   setDownholeApiKey(apiKey)
%   setDownholeApiKey(apiKey, baseUrl)
%
%   Sets the DOWNHOLE_API_KEY (and optional DOWNHOLE_BASE_URL) process
%   environment variables that every other MATLAB example reads via
%   getenv(). Mirrors the PowerShell helper Set-DownholeApiKey.ps1
%   (Session scope) — the values live for the current MATLAB process only,
%   so nothing is written to disk or the shell history.
%
%   Interactive prompt (input hidden from the command window):
%       setDownholeApiKey();
%
%   Verify without revealing the key:
%       setDownholeApiKey('-verify');
%
%   Clear the key:
%       setDownholeApiKey('-clear');
%
%   See also: getSolverSpecReport, /sdk/powershell/examples/Set-DownholeApiKey.ps1.

    if nargin < 1 || isempty(apiKey)
        apiKey = localPromptSecret('Paste DOWNHOLE_API_KEY (hidden): ');
    end

    if ischar(apiKey) || isstring(apiKey)
        apiKey = char(apiKey);
        if strcmpi(apiKey, '-verify')
            localVerify();
            return
        end
        if strcmpi(apiKey, '-clear')
            setenv('DOWNHOLE_API_KEY', '');
            fprintf('[ok] DOWNHOLE_API_KEY cleared for this MATLAB session.\n');
            return
        end
    end

    apiKey = strtrim(char(apiKey));
    apiKey = regexprep(apiKey, '^["'']|["'']$', '');
    if isempty(apiKey)
        error('setDownholeApiKey:empty', 'No key provided.');
    end
    if numel(apiKey) < 16
        warning('setDownholeApiKey:short', ...
            'Key looks unusually short (length=%d). Double-check you pasted the full value.', numel(apiKey));
    end

    setenv('DOWNHOLE_API_KEY', apiKey);
    fprintf('[ok] DOWNHOLE_API_KEY saved (length=%d).\n', numel(apiKey));

    if nargin >= 2 && ~isempty(baseUrl)
        setenv('DOWNHOLE_BASE_URL', char(baseUrl));
        fprintf('[ok] DOWNHOLE_BASE_URL = %s\n', char(baseUrl));
    end
end

function localVerify()
    key = getenv('DOWNHOLE_API_KEY');
    url = getenv('DOWNHOLE_BASE_URL');
    if isempty(key)
        fprintf('[missing] DOWNHOLE_API_KEY is NOT set.\n');
    else
        prefix = key(1:min(7, numel(key)));
        fprintf('[ok] DOWNHOLE_API_KEY set (length=%d, prefix=''%s…'').\n', numel(key), prefix);
    end
    if ~isempty(url)
        fprintf('[ok] DOWNHOLE_BASE_URL = %s\n', url);
    end
end

function value = localPromptSecret(prompt)
    % Try the Java Swing password field first (hidden input); fall back to
    % plain input() for headless/-nodisplay sessions.
    try
        if usejava('awt')
            field = javax.swing.JPasswordField(30);
            javax.swing.JOptionPane.showMessageDialog([], field, prompt, ...
                javax.swing.JOptionPane.QUESTION_MESSAGE);
            value = char(field.getPassword());
            return
        end
    catch
        % ignore, fall through
    end
    value = input(prompt, 's');
end
