import { Database } from "@/lib/store";
import { evaluateRemoteHeartbeat, isLicenseOperational, refreshRemoteHeartbeat } from "@/lib/license";
import { CommercialPlan, RiskLimits } from "@/lib/types";

export const PLAN_LIMITS: Record<CommercialPlan, {
  label: string;
  monthlyPrice: string;
  pinterestAccounts: number;
  seats: number;
  trendResearches: number;
  pinPublishes: number;
  boardCreates: number;
  apiWrites: number;
  features: string[];
}> = {
  starter: {
    label: "Starter",
    monthlyPrice: "¥399-699/月",
    pinterestAccounts: 1,
    seats: 1,
    trendResearches: 10,
    pinPublishes: 5,
    boardCreates: 2,
    apiWrites: 30,
    features: ["趋势研究", "Pin 草稿", "人工审核发布", "基础图板管理"],
  },
  growth: {
    label: "Growth",
    monthlyPrice: "¥1299-1999/月",
    pinterestAccounts: 1,
    seats: 3,
    trendResearches: 30,
    pinPublishes: 20,
    boardCreates: 8,
    apiWrites: 120,
    features: ["OpenClaw 指挥", "图板同步", "API 发布", "审计记录", "远程更新"],
  },
  pro: {
    label: "Pro",
    monthlyPrice: "¥3999-9999/月",
    pinterestAccounts: 3,
    seats: 10,
    trendResearches: 100,
    pinPublishes: 80,
    boardCreates: 25,
    apiWrites: 400,
    features: ["多账号运营", "广告/目录占位流", "高级额度", "专属支持"],
  },
  enterprise: {
    label: "Enterprise",
    monthlyPrice: "私有部署/定制报价",
    pinterestAccounts: 10,
    seats: 30,
    trendResearches: 300,
    pinPublishes: 240,
    boardCreates: 80,
    apiWrites: 1200,
    features: ["私有部署", "团队交付", "API/MCP 集成", "定制工作流"],
  },
};

export type CommercialAction = "trend_research" | "pin_publish" | "board_create" | "api_write";

export function buildCommercialSnapshot(db: Database) {
  const plan = PLAN_LIMITS[db.license.plan] || PLAN_LIMITS.growth;
  const riskLimits: RiskLimits = {
    ...db.riskLimits,
    dailyTrendResearches: Math.min(db.riskLimits.dailyTrendResearches, plan.trendResearches),
    dailyPinPublishes: Math.min(db.riskLimits.dailyPinPublishes, plan.pinPublishes),
    dailyBoardCreates: Math.min(db.riskLimits.dailyBoardCreates, plan.boardCreates),
    dailyApiWrites: Math.min(db.riskLimits.dailyApiWrites, plan.apiWrites),
  };
  const usage = buildDailyUsage(db);
  const remoteHeartbeat = evaluateRemoteHeartbeat(db.license);
  return {
    plan,
    license: db.license,
    remoteHeartbeat,
    riskLimits,
    usage,
    auditEvents: db.auditLogs.slice(0, 12),
    modules: buildCommercialModules(db),
  };
}

export function checkCommercialGate(db: Database, action: CommercialAction, requested = 1) {
  const snapshot = buildCommercialSnapshot(db);
  const licenseCheck = isLicenseOperational(snapshot.license);
  if (!licenseCheck.ok) {
    return {
      ok: false as const,
      status: 402,
      code: licenseCheck.code,
      error: licenseCheck.error,
      snapshot,
    };
  }

  const current = usageForAction(snapshot.usage, action);
  const limit = limitForAction(snapshot.riskLimits, action);
  if (current + requested > limit) {
    return {
      ok: false as const,
      status: 429,
      code: "daily_limit_reached",
      error: `${actionLabel(action)}今日额度不足：${current}/${limit}，本次需要 ${requested}。`,
      action,
      current,
      limit,
      requested,
      snapshot,
    };
  }
  return {
    ok: true as const,
    action,
    current,
    limit,
    remaining: Math.max(0, limit - current),
    snapshot,
  };
}

export async function checkCommercialGateWithHeartbeat(db: Database, action: CommercialAction, requested = 1) {
  if (shouldRefreshRemoteHeartbeat(db)) {
    const result = await refreshRemoteHeartbeat(db.license);
    db.license = {
      ...db.license,
      ...result.license,
    };
    if (result.ok && result.limits) {
      db.riskLimits = {
        ...db.riskLimits,
        ...result.limits,
      };
    }
    db.auditLogs.unshift({
      id: `audit-${Date.now()}`,
      type: "system",
      actor: "system",
      title: result.ok ? "自动远程授权心跳成功" : "自动远程授权心跳失败",
      detail: result.ok
        ? `${db.license.plan} · 租约至 ${db.license.leaseExpiresAt || "-"}`
        : `${result.code}: ${result.error}`,
      status: result.ok ? "completed" : "failed",
      createdAt: new Date().toISOString(),
    });
  }
  return checkCommercialGate(db, action, requested);
}

export function taskAction(type: string): CommercialAction | null {
  if (type === "publish_pin") return "pin_publish";
  if (type === "create_board") return "board_create";
  if (type === "research_trends") return "trend_research";
  if (type === "read_pin_analytics" || type === "catalog_check" || type === "ads_report") return "api_write";
  return null;
}

function buildDailyUsage(db: Database) {
  const today = new Date().toISOString().slice(0, 10);
  const isToday = (value: string | undefined) => String(value || "").slice(0, 10) === today;
  return {
    trendResearches: db.trendResearch.filter((item) => isToday(item.createdAt)).length,
    pinPublishes: db.tasks.filter((item) => isToday(item.createdAt) && item.type === "publish_pin").length,
    boardCreates: db.boards.filter((item) => isToday(item.createdAt)).length,
    apiWrites: db.tasks.filter((item) => isToday(item.createdAt) && item.executorMode === "api").length,
  };
}

function usageForAction(usage: ReturnType<typeof buildDailyUsage>, action: CommercialAction) {
  if (action === "trend_research") return usage.trendResearches;
  if (action === "pin_publish") return usage.pinPublishes;
  if (action === "board_create") return usage.boardCreates;
  return usage.apiWrites;
}

function limitForAction(riskLimits: RiskLimits, action: CommercialAction) {
  if (action === "trend_research") return riskLimits.dailyTrendResearches;
  if (action === "pin_publish") return riskLimits.dailyPinPublishes;
  if (action === "board_create") return riskLimits.dailyBoardCreates;
  return riskLimits.dailyApiWrites;
}

function actionLabel(action: CommercialAction) {
  if (action === "trend_research") return "趋势研究";
  if (action === "pin_publish") return "Pin 发布";
  if (action === "board_create") return "图板创建";
  return "API 写入";
}

function shouldRefreshRemoteHeartbeat(db: Database) {
  const license = db.license;
  const hasRemoteConfig = Boolean(
    (license.remoteServerUrl && license.remoteLicenseKey) ||
    (process.env.PINTEREST_AUTO_LICENSE_SERVER_URL && process.env.PINTEREST_AUTO_LICENSE_KEY)
  );
  if (!hasRemoteConfig) return false;
  if (license.remoteStatus === "expired" || license.remoteStatus === "suspended") return false;
  const now = Date.now();
  const nextMs = new Date(license.nextHeartbeatAt || "").getTime();
  if (!Number.isFinite(nextMs) || nextMs <= now) return true;
  const leaseMs = new Date(license.leaseExpiresAt || "").getTime();
  if (!Number.isFinite(leaseMs)) return true;
  return leaseMs - now <= 10 * 60000;
}

function buildCommercialModules(db: Database) {
  const pendingPublishApprovals = db.pinDrafts.filter((pin) => pin.status === "pending_review").length;
  return [
    {
      title: "趋势研究",
      status: db.trendResearch.length > 0 ? "可用" : "待初始化",
      detail: `${db.trendResearch.length} 组关键词研究`,
    },
    {
      title: "Pin 发布",
      status: pendingPublishApprovals > 0 ? "待确认" : "可用",
      detail: `${pendingPublishApprovals} 个 Pin 草稿待审核，${db.pinDrafts.filter((pin) => pin.status === "published").length} 个已发布`,
    },
    {
      title: "图板管理",
      status: db.boards.some((board) => board.apiBoardId) ? "API 已绑定" : "本地草稿",
      detail: `${db.boards.length} 个图板，${db.boards.filter((board) => board.apiBoardId).length} 个 API 绑定`,
    },
    {
      title: "任务审计",
      status: db.tasks.some((task) => task.status === "failed") ? "需处理" : "正常",
      detail: `${db.tasks.length} 个任务，${db.auditLogs.length} 条审计`,
    },
  ];
}
