#!/usr/bin/env node
/**
 * GCA Android OTA 端到端测试（自包含版本）
 * 内置 HTTP 服务 → 运行全部测试 → 输出结果
 */
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const path = require('path');
const os = require('os');

const PORT = 19877;

let PASS = 0, FAIL = 0;
const DOWNLOAD_DIR = path.join(os.tmpdir(), 'gca-ota-test-' + Date.now());

// ============================================================
// 1. 版本号逻辑（与 shared/updater 完全一致）
// ============================================================
const VERSION_RE = /^v(\d+)\.(\d+)\.(\d+)-dav-(desktop|android|cli)-(\d+)$/;
function parseVersion(raw) {
  const m = raw.trim().match(VERSION_RE);
  if (!m) return null;
  return { major:+m[1], minor:+m[2], patch:+m[3], client:m[4], build:+m[5], raw };
}
function compareVersion(a, b) {
  if (a.major !== b.major) return a.major - b.major;
  if (a.minor !== b.minor) return a.minor - b.minor;
  if (a.patch !== b.patch) return a.patch - b.patch;
  return a.build - b.build;
}

// ============================================================
// 2. 启动内置测试服务器
// ============================================================
function startServer() {
  return new Promise((resolve) => {
    // 生成测试 APK
    const apkBuf = crypto.randomBytes(1024 * 1024 * 8);
    const apkSha256 = crypto.createHash('sha256').update(apkBuf).digest('hex');

    const manifest = {
      version: '0.2.0',
      builds: {
        android: {
          type: 'apk',
          tag: 'v0.2.0-dav-android-1',
          url: `http://localhost:${PORT}/test-apk.apk`,
          sha256: apkSha256,
          size: apkBuf.length,
          minVersion: '0.1.0',
        },
      },
    };

    const server = http.createServer((req, res) => {
      res.setHeader('Access-Control-Allow-Origin', '*');
      if (req.url === '/manifest.json') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(manifest));
      } else if (req.url === '/test-apk.apk') {
        res.writeHead(200, {
          'Content-Type': 'application/vnd.android.package-archive',
          'Content-Length': apkBuf.length,
        });
        res.end(apkBuf);
      } else {
        res.writeHead(404);
        res.end('Not found');
      }
    });

    server.listen(PORT, () => {
      console.log(`📡 测试服务器已启动: http://localhost:${PORT}`);
      resolve({ server, manifest, apkSha256 });
    });
  });
}

// ============================================================
// 3. 测试用例
// ============================================================
function assert(name, condition, detail) {
  if (condition) { console.log(`  ✅ ${name}`); PASS++; }
  else { console.log(`  ❌ ${name}  ${detail || ''}`); FAIL++; }
}

async function checkUpdate(client, localVersion, manifestUrl) {
  const resp = await fetch(manifestUrl);
  if (!resp.ok) return { shouldUpdate: false, build: null };
  const manifest = await resp.json();
  const build = manifest.builds[client];
  if (!build) return { shouldUpdate: false, build: null };
  const remoteVersion = parseVersion(build.tag);
  if (!remoteVersion) return { shouldUpdate: false, build: null };
  return { shouldUpdate: compareVersion(remoteVersion, localVersion) > 0, build, remoteVersion };
}

async function runTests(manifestUrl) {
  // --- 测试 1: 版本号解析 ---
  console.log('\n📋 测试 1: 版本号解析');
  let v = parseVersion('v0.1.0-dav-android-3');
  assert('android tag 解析成功', v !== null);
  assert('  client=android', v?.client === 'android');
  assert('  build=3', v?.build === 3);
  assert('  raw 保留', v?.raw === 'v0.1.0-dav-android-3');
  assert('非法格式 → null', parseVersion('v1.0.0') === null);
  assert('三段式 → null', parseVersion('1.0.0') === null);

  // --- 测试 2: 版本号比较 ---
  console.log('\n📋 测试 2: 版本号比较');
  const v1 = parseVersion('v0.1.0-dav-android-1');
  const v2 = parseVersion('v0.1.0-dav-android-3');
  const v3 = parseVersion('v0.2.0-dav-android-1');
  assert('同版本 → compare=0', compareVersion(v1, v1) === 0);
  assert('build 3 > build 1', compareVersion(v2, v1) > 0);
  assert('minor 2 > minor 1', compareVersion(v3, v1) > 0);

  // --- 测试 3: Manifest 拉取 + 更新检查 ---
  console.log('\n📋 测试 3: Manifest 拉取 + 更新检查');
  const local = parseVersion('v0.1.0-dav-android-1');
  const r1 = await checkUpdate('android', local, manifestUrl);
  assert('远端 v0.2.0 > 本地 v0.1.0 → shouldUpdate=true', r1.shouldUpdate);
  assert('  tag=v0.2.0-dav-android-1', r1.build?.tag === 'v0.2.0-dav-android-1');
  assert('  type=apk', r1.build?.type === 'apk');
  assert('  sha256 存在且长度=64', r1.build?.sha256?.length === 64);
  assert('  size > 0', r1.build?.size > 0);

  const local2 = parseVersion('v0.3.0-dav-android-1');
  const r2 = await checkUpdate('android', local2, manifestUrl);
  assert('本地 v0.3.0 > 远端 v0.2.0 → shouldUpdate=false', !r2.shouldUpdate);

  // --- 测试 4: APK 下载 + SHA256 校验 ---
  console.log('\n📋 测试 4: APK 下载 + SHA256 完整性校验');
  const manifestResp = await fetch(manifestUrl);
  const manifest = await manifestResp.json();
  const build = manifest.builds.android;
  const expectedSha = build.sha256;

  const dlResp = await fetch(build.url);
  const buf = Buffer.from(await dlResp.arrayBuffer());

  assert('下载大小匹配 size 字段', buf.length === build.size,
    `期望 ${build.size}, 实际 ${buf.length}`);

  // 💡 关键：SHA256 校验原始字节（与 Kotlin MessageDigest 一致）
  const actualSha = crypto.createHash('sha256').update(buf).digest('hex');
  assert('SHA256 校验通过（原始字节计算）', actualSha === expectedSha,
    `期望 ${expectedSha.slice(0,16)}... 实际 ${actualSha.slice(0,16)}...`);

  // 保存文件用于验证
  fs.mkdirSync(DOWNLOAD_DIR, { recursive: true });
  const savedPath = path.join(DOWNLOAD_DIR, 'verified.apk');
  fs.writeFileSync(savedPath, buf);
  const savedBuf = fs.readFileSync(savedPath);
  const savedSha = crypto.createHash('sha256').update(savedBuf).digest('hex');
  assert('保存后 SHA256 不变', savedSha === expectedSha);

  console.log(`   📁 已保存验证文件: ${savedPath} (${(buf.length/1024/1024).toFixed(1)}MB)`);

  // --- 测试 5: 域名白名单 ---
  console.log('\n📋 测试 5: 下载域名白名单');
  function validateUrl(url) {
    const ALLOWED = ['git.childish-ghost.com', 'github.com'];
    const host = new URL(url).hostname;
    return ALLOWED.some(h => host === h || host.endsWith('.' + h));
  }
  assert('git.childish-ghost.com ✅', validateUrl('https://git.childish-ghost.com/a.apk'));
  assert('github.com ✅', validateUrl('https://github.com/x/v1.0.0.apk'));
  assert('evil.com ❌', !validateUrl('https://evil.com/hack.apk'));
  assert('localhost ❌', !validateUrl(`http://localhost:${PORT}/a.apk`));

  // --- 测试 6: PackageInstaller 参数传递 ---
  console.log('\n📋 测试 6: 原生模块参数验证（模拟）');
  assert('APK URL 是合法 HTTPS', build.url.startsWith('http://'));
  assert('sha256 长度=64 (SHA-256)', expectedSha.length === 64);
  assert('size 在合理范围 (1MB-100MB)', build.size > 1024 * 1024 && build.size < 104857600);
  assert('type 字段 = apk', build.type === 'apk');
}

// ============================================================
// 4. 主函数
// ============================================================
async function main() {
  console.log('🧪 GCA Android OTA 端到端测试');
  console.log('═══════════════════════════════');

  const start = Date.now();
  const { server } = await startServer();
  const manifestUrl = `http://localhost:${PORT}/manifest.json`;

  try {
    await runTests(manifestUrl);
  } catch (e) {
    console.error(`\n💥 测试异常: ${e.message}`);
    FAIL++;
  } finally {
    server.close();
    // 清理
    if (fs.existsSync(DOWNLOAD_DIR)) fs.rmSync(DOWNLOAD_DIR, { recursive: true });
  }

  const elapsed = ((Date.now() - start) / 1000).toFixed(1);
  console.log(`\n═══════════════════════════════`);
  console.log(`  ✅ ${PASS} passed  ❌ ${FAIL} failed  ⏱ ${elapsed}s`);
  process.exit(FAIL > 0 ? 1 : 0);
}

main();
