import { describe, expect, test } from 'bun:test';
import { parseLoginProbe } from './os-user-claude';

// Pins the shape of the answer `/agent-status` gives a member about their own agent.
//
// The version before this one decided with `out.includes('bin')` / `out.includes('cred')` against a string
// that merged stdout and stderr — and both markers are substrings of the paths the probe tests. A shell trace
// echoing the command was enough to report a member as installed and signed in when neither was true,
// verified on the live server against an account that had never logged in. It failed in the unsafe direction:
// the endpoint exists to explain a broken agent, and that is the mode where it explains the wrong thing.
//
// So the assertions below are mostly about what CANNOT move the answer.

describe('parseLoginProbe', () => {
  test('reads both flags by position', () => {
    expect(parseLoginProbe('11')).toEqual({ installed: true, loggedIn: true });
    expect(parseLoginProbe('10')).toEqual({ installed: true, loggedIn: false });
    expect(parseLoginProbe('01')).toEqual({ installed: false, loggedIn: true });
    expect(parseLoginProbe('00')).toEqual({ installed: false, loggedIn: false });
  });

  test('the freshly provisioned case: installed, not signed in', () => {
    // What a member sees before they run `claude` once themselves — the case the UI renders instructions for.
    expect(parseLoginProbe('10')).toEqual({ installed: true, loggedIn: false });
  });

  test('a trace of the probe cannot set either flag', () => {
    // Exactly the stderr the live server captured under `sh -x`, now on the channel the answer is read from.
    // Under the old substring match this returned true/true.
    const trace =
      '+ test -x /data/jg@pertento.ai/home/.local/bin/claude\n' +
      '+ test -s /data/jg@pertento.ai/home/.claude/.credentials.json\n';
    expect(parseLoginProbe(trace)).toEqual({ installed: false, loggedIn: false });
  });

  test('the paths themselves cannot set either flag', () => {
    expect(parseLoginProbe('/home/x/.local/bin/claude')).toEqual({ installed: false, loggedIn: false });
    expect(parseLoginProbe('/home/x/.claude/.credentials.json')).toEqual({ installed: false, loggedIn: false });
  });

  test('no output refuses rather than assuming', () => {
    // A failed spawn must not read as a working agent.
    expect(parseLoginProbe('')).toEqual({ installed: false, loggedIn: false });
  });

  test('a sudo banner or any other prefix cannot shift the positions into truth', () => {
    expect(parseLoginProbe('sudo: a password is required\n')).toEqual({ installed: false, loggedIn: false });
  });
});
