import { describe, it } from 'node:test';
import { strict as assert } from 'node:assert';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';

import { resolveHostedRuntimeTargetInfo } from '../HostedRuntimeTarget';

const thisDir = path.dirname(fileURLToPath(import.meta.url));

describe('resolveHostedRuntimeTargetInfo', () => {
  it('keeps asset/platform/session/selected roots separate', () => {
    const host = {
      getAttribute(name: string): string | null {
        if (name === 'runtime-root') return 'test-user-1.DIRECTOR.SESSION-ABC';
        if (name === 'authority-root') return 'SPACE-HIVECAST';
        return null;
      },
      dataset: {
        assetHostRoot: 'SPACE-HIVECAST',
        platformServiceRoot: 'SPACE-HIVECAST',
        sessionAuthorityRoot: 'test-user-1',
        selectedAuthorityRoot: 'test-user-1',
        selectableAuthorityRoots: 'test-user-1',
        platformRoot: 'SPACE-HIVECAST',
        authenticated: 'true',
        isPlatformAdmin: 'false',
      },
    };

    assert.deepEqual(resolveHostedRuntimeTargetInfo(host), {
      runtimeRoot: 'test-user-1.DIRECTOR.SESSION-ABC',
      runtimeInstanceRoot: 'test-user-1.DIRECTOR.SESSION-ABC',
      authorityRoot: 'test-user-1',
      assetHostRoot: 'SPACE-HIVECAST',
      platformServiceRoot: 'SPACE-HIVECAST',
      sessionAuthorityRoot: 'test-user-1',
      selectedAuthorityRoot: 'test-user-1',
      platformRoot: 'SPACE-HIVECAST',
      targetSource: '',
      targetKind: '',
      requestedRoot: '',
      unavailableReason: '',
      isAuthenticated: true,
      isPlatformAdmin: false,
      selectableAuthorityRoots: ['test-user-1'],
    });
  });

  it('requests browser NATS credentials for selectedAuthorityRoot, not sessionAuthorityRoot', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.match(source, /const selectedAuthorityRoot = \(this\.dataset\.selectedAuthorityRoot \?\? ''\)\.trim\(\);/);
    assert.match(source, /: \(selectedAuthorityRoot \|\| requestedDaemonRoot\);/);
    assert.doesNotMatch(source, /principalAuthorityRoot[\s\S]{0,220}requestedDaemonRoot === platformRoot/);
  });

  it('does not let addressRoot decide session or authority context roots', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.doesNotMatch(source, /bootstrap\.authenticated \? bootstrap\.addressRoot/);
    assert.doesNotMatch(source, /const authorityRootService =[\s\S]{0,120}\|\| this\.dataset\.addressRoot/);
  });

  it('does not promote anonymous platform bootstrap into selectedAuthorityRoot', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.match(source, /parseBootstrapAuthorityContext\(bootstrap\.authorityContext\)/);
    assert.match(source, /const selectedAuthorityRoot = authorityContext\.selectedAuthorityRoot \?\? '';/);
    assert.doesNotMatch(source, /bootstrapSelectedAuthorityRoot/);
    assert.doesNotMatch(source, /bootstrapAuthorityContextRoot/);
  });

  it('does not let runtime summary addressRoot re-home selectedAuthorityRoot', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.match(source, /_hostedAuthorityRootFromBootstrap/);
    assert.doesNotMatch(source, /_selectHostedAuthorityRoot/);
    assert.doesNotMatch(source, /summaryAuthorityRoot/);
    assert.doesNotMatch(source, /summary\.authority\?\.addressRoot/);
  });

  it('skips Phase B platform probes for normal user authority sessions', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.match(source, /const isNormalUserAuthoritySession = bootstrapAuthenticated/);
    assert.match(source, /userAuthorityRoot !== serviceRoot/);
    assert.match(source, /Phase B platform probe skipped for user authority session/);
  });

  it('does not refresh bus tokens through a platform auth target for normal users', () => {
    const source = fs.readFileSync(path.join(thisDir, '..', 'MatrixDSLHost.ts'), 'utf8');
    assert.match(source, /_shouldSkipBusTokenRefreshForTarget\(authTarget\)/);
    assert.match(source, /targetRoot !== userAuthorityRoot/);
    assert.match(source, /Bus token refresh skipped for platform auth target in user authority session/);
  });
});
