import { describe, it, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';
import axios from 'axios';
import { mkdtemp, writeFile, chmod, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
import { checkRequiredEnv, verifyGiteaToken, verifyCommentToken, verifyLLM, fetchCodexModels, runPreflight } from '../preflight.js';

const LLM_ENV_KEYS = [
  'AI_ASSISTANT_CLI', 'MODEL', 'OPENCODE_MODEL', 'PATH',
];
const ORIGINAL_PATH = process.env.PATH;

function clearLLMEnv() {
  for (const k of LLM_ENV_KEYS) delete process.env[k];
}

let tempDir;

afterEach(async () => {
  mock.restoreAll();
  clearLLMEnv();
  process.env.PATH = ORIGINAL_PATH;
  if (tempDir) await rm(tempDir, { recursive: true, force: true });
  tempDir = null;
});

async function installFakeCLI(command = 'codex') {
  tempDir = await mkdtemp(join(tmpdir(), 'preflight-cli-test-'));
  const script = join(tempDir, command);
  await writeFile(script, '#!/bin/sh\nexit 0\n');
  await chmod(script, 0o755);
  process.env.PATH = tempDir;
}

describe('checkRequiredEnv', () => {
  it('reports all three missing when nothing provided', () => {
    const result = checkRequiredEnv({ token: '', repo: '', pr: '' });
    assert.equal(result.ok, false);
    assert.deepEqual(result.missing, ['GITEA_TOKEN', 'GITEA_REPOSITORY', 'PR_NUMBER']);
  });

  it('reports only the missing ones', () => {
    const result = checkRequiredEnv({ token: 't', repo: '', pr: '5' });
    assert.equal(result.ok, false);
    assert.deepEqual(result.missing, ['GITEA_REPOSITORY']);
  });

  it('ok when all provided', () => {
    const result = checkRequiredEnv({ token: 't', repo: 'owner/repo', pr: '5' });
    assert.equal(result.ok, true);
    assert.deepEqual(result.missing, []);
  });
});

describe('verifyGiteaToken', () => {
  it('ok when repo endpoint returns successfully', async () => {
    let capturedUrl, capturedOpts;
    mock.method(axios, 'get', async (url, opts) => {
      capturedUrl = url;
      capturedOpts = opts;
      return { data: { full_name: 'owner/repo' } };
    });

    const result = await verifyGiteaToken('tok', 'owner/repo');

    assert.equal(result.ok, true);
    assert.ok(capturedUrl.includes('/api/v1/repos/owner/repo'));
    assert.equal(capturedOpts.headers['Authorization'], 'token tok');
  });

  it('fails with HTTP status when token is invalid', async () => {
    mock.method(axios, 'get', async () => {
      const e = new Error('Unauthorized');
      e.response = { status: 401 };
      throw e;
    });

    const result = await verifyGiteaToken('bad', 'owner/repo');

    assert.equal(result.ok, false);
    assert.match(result.error, /HTTP 401/);
  });
});

describe('verifyCommentToken', () => {
  it('skips when no comment token provided', async () => {
    const result = await verifyCommentToken('');
    assert.deepEqual(result, { ok: true, skipped: true });
  });

  it('ok when /user returns successfully', async () => {
    let capturedUrl, capturedOpts;
    mock.method(axios, 'get', async (url, opts) => {
      capturedUrl = url;
      capturedOpts = opts;
      return { data: { login: 'bot' } };
    });

    const result = await verifyCommentToken('ctok');

    assert.equal(result.ok, true);
    assert.ok(capturedUrl.endsWith('/api/v1/user'));
    assert.equal(capturedOpts.headers['Authorization'], 'token ctok');
  });

  it('fails when comment token is invalid', async () => {
    mock.method(axios, 'get', async () => {
      const e = new Error('Unauthorized');
      e.response = { status: 401 };
      throw e;
    });

    const result = await verifyCommentToken('bad');

    assert.equal(result.ok, false);
    assert.match(result.error, /HTTP 401/);
  });
});

describe('verifyLLM', () => {
  it('fails when no supported assistant CLI is detected', async () => {
    clearLLMEnv();
    process.env.AI_ASSISTANT_CLI = 'no-such-ai-cli';
    process.env.PATH = '';

    const result = await verifyLLM();

    assert.equal(result.ok, false);
    assert.match(result.error, /AI 助理 CLI/);
  });

  it('passes when a supported assistant CLI is detected and the model is in the codex list', async () => {
    clearLLMEnv();
    await installFakeCLI('codex');
    process.env.AI_ASSISTANT_CLI = 'codex';
    process.env.MODEL = 'gpt-5.4-mini';

    const result = await verifyLLM({
      fetchCodexModelsFn: async () => ({ ok: true, slugs: ['gpt-5.5', 'gpt-5.4-mini'] }),
    });

    assert.equal(result.ok, true);
    assert.equal(result.provider, 'codex');
    assert.equal(result.command, 'codex');
    assert.equal(result.model, 'gpt-5.4-mini');
    assert.deepEqual(result.models, ['gpt-5.5', 'gpt-5.4-mini']);
  });

  it('fails when codex auth is invalid (model list check reports 401)', async () => {
    clearLLMEnv();
    await installFakeCLI('codex');
    process.env.AI_ASSISTANT_CLI = 'codex';
    process.env.MODEL = 'gpt-5.4-mini';

    const result = await verifyLLM({
      fetchCodexModelsFn: async () => ({ ok: false, error: 'codex 認證失效（HTTP 401）——token 已被撤銷或過期，請重新登入 codex 並更新 LLM_OAUTH secret' }),
    });

    assert.equal(result.ok, false);
    assert.equal(result.provider, 'codex');
    assert.match(result.error, /HTTP 401/);
    assert.match(result.error, /LLM_OAUTH/);
  });

  it('fails when the configured model is not in the codex available list', async () => {
    clearLLMEnv();
    await installFakeCLI('codex');
    process.env.AI_ASSISTANT_CLI = 'codex';
    process.env.MODEL = 'gpt-9-imaginary';

    const result = await verifyLLM({
      fetchCodexModelsFn: async () => ({ ok: true, slugs: ['gpt-5.5', 'gpt-5.4-mini'] }),
    });

    assert.equal(result.ok, false);
    assert.match(result.error, /不在 codex 可用清單/);
    assert.match(result.error, /gpt-5\.4-mini/);
  });

  it('fails when a requested CLI is not installed', async () => {
    clearLLMEnv();
    process.env.AI_ASSISTANT_CLI = 'missing-cli';
    process.env.PATH = '';

    const result = await verifyLLM();

    assert.equal(result.ok, false);
    assert.match(result.error, /AI 助理 CLI/);
  });

});

describe('fetchCodexModels', () => {
  async function writeAuth(json) {
    tempDir = await mkdtemp(join(tmpdir(), 'codex-auth-test-'));
    const authPath = join(tempDir, 'auth.json');
    await writeFile(authPath, JSON.stringify(json));
    return authPath;
  }

  it('returns the model slugs on HTTP 200', async () => {
    const authPath = await writeAuth({ tokens: { access_token: 'tok', account_id: 'acc' } });
    let capturedUrl, capturedHeaders;
    const result = await fetchCodexModels({
      authPath,
      fetchImpl: async (url, opts) => {
        capturedUrl = url;
        capturedHeaders = opts.headers;
        return { status: 200, ok: true, json: async () => ({ models: [{ slug: 'gpt-5.5' }, { slug: 'gpt-5.4-mini' }] }) };
      },
    });
    assert.deepEqual(result, { ok: true, slugs: ['gpt-5.5', 'gpt-5.4-mini'] });
    assert.match(capturedUrl, /client_version=/);
    assert.equal(capturedHeaders['Authorization'], 'Bearer tok');
    assert.equal(capturedHeaders['chatgpt-account-id'], 'acc');
  });

  it('reports an auth failure on HTTP 401', async () => {
    const authPath = await writeAuth({ tokens: { access_token: 'revoked' } });
    const result = await fetchCodexModels({
      authPath,
      fetchImpl: async () => ({ status: 401, ok: false, json: async () => ({}) }),
    });
    assert.equal(result.ok, false);
    assert.match(result.error, /HTTP 401/);
    assert.match(result.error, /LLM_OAUTH/);
  });

  it('fails when the auth file cannot be read', async () => {
    const result = await fetchCodexModels({
      authPath: join(tmpdir(), 'definitely-missing-codex-auth-xyz.json'),
      fetchImpl: async () => ({ status: 200, ok: true, json: async () => ({ models: [] }) }),
    });
    assert.equal(result.ok, false);
    assert.match(result.error, /無法讀取 codex 認證檔/);
  });

  it('fails when the auth file lacks an access_token', async () => {
    const authPath = await writeAuth({ tokens: {} });
    const result = await fetchCodexModels({ authPath, fetchImpl: async () => ({ status: 200, ok: true, json: async () => ({}) }) });
    assert.equal(result.ok, false);
    assert.match(result.error, /缺少 tokens\.access_token/);
  });
});

describe('runPreflight', () => {
  function makeDeps(overrides = {}) {
    return {
      checkEnv: () => ({ ok: true, missing: [] }),
      verifyToken: async () => ({ ok: true }),
      verifyComment: async () => ({ ok: true }),
      verifyRemote: () => ({ ok: true }),
      verifyLLMFn: async () => ({ ok: true, provider: 'codex' }),
      ...overrides,
    };
  }

  it('returns false and stops early when required env is missing', async () => {
    const result = await runPreflight();
    assert.equal(result, false);
  });

  it('returns true when every verification step succeeds', async () => {
    const result = await runPreflight('/ws', makeDeps());
    assert.equal(result, true);
  });

  it('returns true when the comment token check is skipped', async () => {
    const result = await runPreflight('/ws', makeDeps({
      verifyComment: async () => ({ ok: true, skipped: true }),
    }));
    assert.equal(result, true);
  });

  it('returns false when the Gitea token check fails', async () => {
    let remoteCalled = false;
    const result = await runPreflight('/ws', makeDeps({
      verifyToken: async () => ({ ok: false, error: 'HTTP 401' }),
      verifyRemote: () => { remoteCalled = true; return { ok: true }; },
    }));
    assert.equal(result, false);
    assert.equal(remoteCalled, false, 'should stop before later checks');
  });

  it('returns false when the comment token check fails', async () => {
    const result = await runPreflight('/ws', makeDeps({
      verifyComment: async () => ({ ok: false, error: 'HTTP 401' }),
    }));
    assert.equal(result, false);
  });

  it('returns false when git remote access fails', async () => {
    let llmCalled = false;
    const result = await runPreflight('/ws', makeDeps({
      verifyRemote: () => ({ ok: false, error: 'auth failed' }),
      verifyLLMFn: async () => { llmCalled = true; return { ok: true }; },
    }));
    assert.equal(result, false);
    assert.equal(llmCalled, false, 'should stop before the LLM check');
  });

  it('returns false when LLM verification fails', async () => {
    const result = await runPreflight('/ws', makeDeps({
      verifyLLMFn: async () => ({ ok: false, error: 'AI 助理 CLI 驗證失敗' }),
    }));
    assert.equal(result, false);
  });

  it('passes the workspace through to the remote-access check', async () => {
    let captured;
    await runPreflight('/custom/ws', makeDeps({
      verifyRemote: (ws) => { captured = ws; return { ok: true }; },
    }));
    assert.equal(captured, '/custom/ws');
  });
});
