import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import * as path from 'path';

const ORIG_ENV = { ...process.env };
const MOCK_HOME = '/home/testuser';

let mockPlatform: NodeJS.Platform = 'linux';
let mockProcVersion: string | Error = 'Linux 6.5.0-generic';

vi.mock('os', async () => {
  const actual = await vi.importActual<typeof import('os')>('os');
  return {
    ...actual,
    platform: () => mockPlatform,
    homedir: () => MOCK_HOME,
  };
});

vi.mock('fs', async () => {
  const actual = await vi.importActual<typeof import('fs')>('fs');
  return {
    ...actual,
    default: actual,
    readFileSync: (p: any, ...rest: any[]) => {
      if (typeof p === 'string' && p === '/proc/version') {
        if (mockProcVersion instanceof Error) throw mockProcVersion;
        return mockProcVersion;
      }
      return (actual.readFileSync as any)(p, ...rest);
    },
  };
});

describe('verify.ts platform helpers', () => {
  beforeEach(() => {
    vi.resetModules();
    delete process.env.WSL_DISTRO_NAME;
    delete process.env.WSL_INTEROP;
    delete process.env.LOCALAPPDATA;
    mockPlatform = 'linux';
    mockProcVersion = 'Linux 6.5.0-generic';
  });

  afterEach(() => {
    process.env = { ...ORIG_ENV };
  });

  it('detectPlatform returns linux-wsl when WSL env set', async () => {
    mockPlatform = 'linux';
    process.env.WSL_DISTRO_NAME = 'Ubuntu';
    const { detectPlatform } = await import('../../scripts/verify');
    expect(detectPlatform()).toBe('linux-wsl');
  });

  it('detectPlatform returns darwin on macOS', async () => {
    mockPlatform = 'darwin';
    const { detectPlatform } = await import('../../scripts/verify');
    expect(detectPlatform()).toBe('darwin');
  });

  it('isWindowsMountPath flags /mnt/c/', async () => {
    const { isWindowsMountPath } = await import('../../scripts/verify');
    expect(isWindowsMountPath('/mnt/c/Users/x')).toBe(true);
    expect(isWindowsMountPath('/home/x')).toBe(false);
  });

  it('resolveProxyInstallPath uses Library on macOS', async () => {
    const { resolveProxyInstallPath } = await import('../../scripts/verify');
    expect(resolveProxyInstallPath('darwin')).toBe(
      path.join(MOCK_HOME, 'Library', 'Application Support', 'priority-forge', 'mcp-proxy.js')
    );
  });

  it('resolveProxyInstallPath uses XDG on WSL (NOT /mnt/c)', async () => {
    const { resolveProxyInstallPath } = await import('../../scripts/verify');
    expect(resolveProxyInstallPath('linux-wsl')).toBe(
      path.join(MOCK_HOME, '.local', 'share', 'priority-forge', 'mcp-proxy.js')
    );
  });

  it('resolveProxyInstallPath uses %LOCALAPPDATA% on Windows', async () => {
    process.env.LOCALAPPDATA = 'C:\\Users\\fried\\AppData\\Local';
    vi.resetModules();
    const { resolveProxyInstallPath } = await import('../../scripts/verify');
    expect(resolveProxyInstallPath('win32')).toBe(
      path.join('C:\\Users\\fried\\AppData\\Local', 'priority-forge', 'mcp-proxy.js')
    );
  });
});
