/**
 * License 验证器
 * 读取、验证和管理项目 License
 */

const fs = require("fs");
const path = require("path");
const { decodeLicenseKey } = require("./license-crypto");

const LICENSE_FILE = ".aineos.license";

const TIER_NAMES = { 0: "free", 1: "team", 2: "enterprise" };
const TIER_LABELS = { 0: "Free", 1: "Team", 2: "Enterprise" };

const FREE_FEATURES = ["crud", "check", "list", "read", "write"];
const TEAM_FEATURES = [...FREE_FEATURES, "heal", "predict", "hitl-full", "pipeline", "no-watermark"];
const ENTERPRISE_FEATURES = [...TEAM_FEATURES, "unlimited-api", "priority-support", "custom-binding"];

function getFeaturesByTier(tier) {
  const t = typeof tier === "string" ? { free: 0, team: 1, enterprise: 2 }[tier] : tier;
  if (t === 2) return ENTERPRISE_FEATURES;
  if (t === 1) return TEAM_FEATURES;
  return FREE_FEATURES;
}

/**
 * 验证 License Key 字符串
 */
function validateLicense(key) {
  const result = decodeLicenseKey(key);
  if (!result.valid) return result;

  const { payload } = result;
  const now = Date.now();
  const expired = payload.e < now;
  const tier = TIER_NAMES[payload.t] || "free";
  const daysRemaining = Math.max(0, Math.ceil((payload.e - now) / 86400000));

  return {
    valid: !expired,
    expired,
    tier,
    tierLabel: TIER_LABELS[payload.t] || "Free",
    expiresAt: new Date(payload.e).toISOString(),
    daysRemaining,
    features: getFeaturesByTier(payload.t),
    licensee: payload.l || "",
    binding: payload.b || "",
    payload,
  };
}

/**
 * 读取项目中的 .aineos.license 文件
 */
function readLicenseFile(projectRoot) {
  const root = projectRoot || process.cwd();
  const p = path.join(root, LICENSE_FILE);
  if (!fs.existsSync(p)) return null;
  try {
    return JSON.parse(fs.readFileSync(p, "utf-8"));
  } catch {
    return null;
  }
}

/**
 * 写入 .aineos.license 文件
 */
function writeLicenseFile(projectRoot, data) {
  const p = path.join(projectRoot, LICENSE_FILE);
  fs.writeFileSync(p, JSON.stringify(data, null, 2), "utf-8");
}

/**
 * 检查当前项目 License 状态
 */
function checkLicenseStatus(projectRoot) {
  const file = readLicenseFile(projectRoot);
  if (!file || !file.key) {
    return { valid: false, tier: "free", tierLabel: "Free", activated: false, features: FREE_FEATURES };
  }
  const result = validateLicense(file.key);
  return {
    ...result,
    activated: true,
    activatedAt: file.activatedAt,
    key: file.key,
  };
}

/**
 * 激活 License
 */
function activateLicense(key, projectRoot) {
  const validated = validateLicense(key);
  if (!validated.valid) {
    return { success: false, error: validated.error || "License Key 无效" };
  }
  writeLicenseFile(projectRoot, {
    key,
    activatedAt: new Date().toISOString(),
    payload: validated.payload,
  });
  return {
    success: true,
    tier: validated.tier,
    tierLabel: validated.tierLabel,
    expiresAt: validated.expiresAt,
    daysRemaining: validated.daysRemaining,
    message: `License 激活成功 — ${validated.tierLabel} 版`,
  };
}

/**
 * 解除 License
 */
function deactivateLicense(projectRoot) {
  const p = path.join(projectRoot, LICENSE_FILE);
  if (fs.existsSync(p)) {
    fs.unlinkSync(p);
    return { success: true };
  }
  return { success: true, message: "License 文件不存在，已为 Free 模式" };
}

/**
 * 检查功能是否可用
 */
function isFeatureAvailable(feature, projectRoot) {
  const status = checkLicenseStatus(projectRoot);
  return status.features.includes(feature);
}

module.exports = {
  validateLicense,
  checkLicenseStatus,
  activateLicense,
  deactivateLicense,
  isFeatureAvailable,
  readLicenseFile,
  writeLicenseFile,
  getFeaturesByTier,
  TIER_NAMES,
  TIER_LABELS,
};
