const deepFreeze = (value) => {
  if (!value || typeof value !== "object" || Object.isFrozen(value)) return value;
  for (const nested of Object.values(value)) deepFreeze(nested);
  return Object.freeze(value);
};

// This revision is embedded in existing entitlement tickets and must remain stable.
export const RUNRAIL_PLAN_CATALOG_REVISION = "runrail-plans-2026-07-24-v1";
export const RUNRAIL_BILLING_OFFER_REVISION = "runrail-offers-2026-08-01-v3";
export const RUNRAIL_BUYER_SCOPES = deepFreeze(["business", "consumer"]);
export const RUNRAIL_IMPLEMENTED_PLAN_CODES = deepFreeze(["starter", "pro"]);
export const RUNRAIL_SELF_SERVE_DELIVERY_READY_PLAN_CODES = deepFreeze([
  "starter",
  "pro"
]);

export const RUNRAIL_PLAN_CATALOG = deepFreeze([
  {
    code: "starter",
    name: "Starter",
    amountLabel: "EUR 19.99/mo",
    amountCents: 1999,
    currency: "eur",
    billingInterval: "month",
    billingIntervalCount: 1,
    taxBehavior: "exclusive",
    taxDisplay: "plus applicable tax",
    includedSeats: 1,
    maxDevices: 1,
    selfServe: true,
    stripePriceEnv: "VEYACT_STRIPE_PRICE_STARTER",
    consumerOffer: {
      amountLabel: "EUR 19.99/mo incl. VAT",
      amountCents: 1999,
      currency: "eur",
      billingInterval: "month",
      billingIntervalCount: 1,
      taxBehavior: "inclusive",
      taxDisplay: "total monthly price including applicable VAT",
      selfServe: true,
      stripePriceEnv: "VEYACT_STRIPE_PRICE_CONSUMER_STARTER",
      intendedBuyer: "Individual developer or private user",
      combinedAudience: "Individual developer or independent software business",
      combinedSummary: "The complete local review foundation for one user and one device."
    },
    intendedBuyer: "Independent software business",
    summary: "The complete local review foundation for one authorized business user and one device.",
    features: [
      "guided-sample",
      "candidate-branch-review",
      "audit-export",
      "deterministic-advisory",
      "deepseek-byok-advisory"
    ],
    access: [
      "Runrail Desktop and CLI for Windows, macOS, Linux, and WSL2",
      "bounded local candidate review, Review Coverage, and Agent Assurance",
      "exact local history hydration and checksum Change Passports",
      "aggregate external evidence receipts without verdict authority",
      "offline deterministic recommendations",
      "optional DeepSeek BYOK advisory with no execution authority",
      "manual onboarding and billing support"
    ]
  },
  {
    code: "pro",
    name: "Pro",
    amountLabel: "EUR 49/mo",
    amountCents: 4900,
    currency: "eur",
    billingInterval: "month",
    billingIntervalCount: 1,
    taxBehavior: "exclusive",
    taxDisplay: "plus applicable tax",
    includedSeats: 1,
    maxDevices: 3,
    selfServe: true,
    stripePriceEnv: "VEYACT_STRIPE_PRICE_PRO",
    consumerOffer: {
      amountLabel: "EUR 49/mo incl. VAT",
      amountCents: 4900,
      currency: "eur",
      billingInterval: "month",
      billingIntervalCount: 1,
      taxBehavior: "inclusive",
      taxDisplay: "total monthly price including applicable VAT",
      selfServe: true,
      stripePriceEnv: "VEYACT_STRIPE_PRICE_CONSUMER_PRO",
      intendedBuyer: "Individual power user",
      combinedAudience: "Individual power user or independent software business",
      combinedSummary: "Deeper local review workflows for one user across multiple devices."
    },
    intendedBuyer: "Independent business or authorized sole-trader operator",
    summary: "Deeper local review workflows for one operator across multiple devices.",
    features: [
      "guided-sample",
      "candidate-branch-review",
      "audit-export",
      "deterministic-advisory",
      "deepseek-byok-advisory",
      "revision-comparison",
      "reusable-policy-profiles",
      "advanced-evidence-exports"
    ],
    access: [
      "everything in Starter",
      "three registered devices",
      "Desktop Revision Workspace, Trust Profiles, and weekly reports",
      "device-signed passports and inspectable ProofGraph evidence",
      "repository-local Agent Outcome Ledger with sample uncertainty",
      "equal-basis Candidate Tournament review-order receipts"
    ]
  },
  {
    code: "team",
    name: "Team",
    amountLabel: "EUR 99/mo",
    amountCents: 9900,
    currency: "eur",
    billingInterval: "month",
    billingIntervalCount: 1,
    taxBehavior: "exclusive",
    taxDisplay: "plus applicable tax",
    includedSeats: 5,
    maxDevices: 10,
    selfServe: true,
    stripePriceEnv: "VEYACT_STRIPE_PRICE_TEAM",
    consumerOffer: null,
    intendedBuyer: "Small engineering team",
    summary: "Shared governance and evidence workflows for a five-seat engineering team.",
    features: [
      "guided-sample",
      "candidate-branch-review",
      "audit-export",
      "deterministic-advisory",
      "deepseek-byok-advisory",
      "revision-comparison",
      "reusable-policy-profiles",
      "advanced-evidence-exports",
      "member-administration",
      "shared-policy-bundles",
      "team-audit-index"
    ],
    access: [
      "everything in Pro",
      "five included seats and ten registered devices",
      "member administration",
      "signed shared policy bundles",
      "source-free team audit index"
    ]
  },
  {
    code: "business",
    name: "Business",
    amountLabel: "EUR 199/mo",
    amountCents: 19900,
    currency: "eur",
    billingInterval: "month",
    billingIntervalCount: 1,
    taxBehavior: "exclusive",
    taxDisplay: "plus applicable tax",
    includedSeats: 15,
    maxDevices: 30,
    selfServe: true,
    stripePriceEnv: "VEYACT_STRIPE_PRICE_BUSINESS",
    consumerOffer: null,
    intendedBuyer: "Organization requiring stronger controls",
    summary: "Organization-level policy enforcement, evidence, retention, and support.",
    features: [
      "guided-sample",
      "candidate-branch-review",
      "audit-export",
      "deterministic-advisory",
      "deepseek-byok-advisory",
      "revision-comparison",
      "reusable-policy-profiles",
      "advanced-evidence-exports",
      "member-administration",
      "shared-policy-bundles",
      "team-audit-index",
      "organization-policy-enforcement",
      "compliance-evidence-exports",
      "configurable-metadata-retention",
      "priority-support"
    ],
    access: [
      "everything in Team",
      "fifteen included seats and thirty registered devices",
      "organization-enforced policies",
      "consolidated compliance evidence exports",
      "configurable source-free metadata retention and priority support"
    ]
  },
  {
    code: "enterprise",
    name: "Enterprise",
    amountLabel: "Custom",
    amountCents: null,
    currency: "eur",
    billingInterval: "contract",
    billingIntervalCount: null,
    taxBehavior: "contract",
    taxDisplay: "tax treatment defined in contract",
    includedSeats: "custom",
    maxDevices: "custom",
    selfServe: false,
    stripePriceEnv: null,
    consumerOffer: null,
    intendedBuyer: "Organization with custom security and procurement requirements",
    summary: "A contracted deployment, security, identity, retention, and support review.",
    features: [
      "guided-sample",
      "candidate-branch-review",
      "audit-export",
      "deterministic-advisory",
      "deepseek-byok-advisory",
      "revision-comparison",
      "reusable-policy-profiles",
      "advanced-evidence-exports",
      "member-administration",
      "shared-policy-bundles",
      "team-audit-index",
      "organization-policy-enforcement",
      "compliance-evidence-exports",
      "configurable-metadata-retention",
      "priority-support",
      "enterprise-sso-review",
      "private-deployment-review",
      "custom-support-sla"
    ],
    access: [
      "everything in Business",
      "custom seats, devices, retention, and support terms",
      "SSO and SAML review",
      "private deployment and procurement review",
      "contracted security and service-level terms"
    ]
  }
]);

export function runrailPlanForCode(code) {
  const normalized = String(code || "").trim().toLowerCase();
  return RUNRAIL_PLAN_CATALOG.find((plan) => plan.code === normalized) || null;
}

export function runrailPlanDeliveryStatus(planOrCode) {
  const plan = typeof planOrCode === "string" ? runrailPlanForCode(planOrCode) : planOrCode;
  if (!plan) return "unknown";
  if (!plan.selfServe) return "contract";
  return RUNRAIL_SELF_SERVE_DELIVERY_READY_PLAN_CODES.includes(plan.code)
    ? "shipped"
    : "planned";
}

export function runrailPlanImplementationStatus(planOrCode) {
  const plan = typeof planOrCode === "string" ? runrailPlanForCode(planOrCode) : planOrCode;
  if (!plan) return "unknown";
  if (!plan.selfServe) return "requirements-discussion";
  return RUNRAIL_IMPLEMENTED_PLAN_CODES.includes(plan.code)
    ? "implemented"
    : "roadmap";
}

export function runrailPlanDeliveryReady(planOrCode) {
  return runrailPlanDeliveryStatus(planOrCode) === "shipped";
}

export function selfServeRunrailPlans() {
  return RUNRAIL_PLAN_CATALOG.filter((plan) => plan.selfServe);
}

export function runrailOfferForPlan(planOrCode, buyerScope = "business") {
  const plan = typeof planOrCode === "string" ? runrailPlanForCode(planOrCode) : planOrCode;
  const scope = String(buyerScope || "").trim().toLowerCase();
  if (!plan || !RUNRAIL_BUYER_SCOPES.includes(scope)) return null;

  if (scope === "consumer") {
    if (!plan.consumerOffer?.selfServe) return null;
    return deepFreeze({
      buyerScope: "consumer",
      priceMode: "configured",
      amountLabel: plan.consumerOffer.amountLabel,
      amountCents: plan.consumerOffer.amountCents,
      currency: plan.consumerOffer.currency,
      billingInterval: plan.consumerOffer.billingInterval,
      billingIntervalCount: plan.consumerOffer.billingIntervalCount,
      taxBehavior: plan.consumerOffer.taxBehavior,
      taxDisplay: plan.consumerOffer.taxDisplay,
      selfServe: true,
      stripePriceEnv: plan.consumerOffer.stripePriceEnv,
      intendedBuyer: plan.consumerOffer.intendedBuyer
    });
  }

  if (!plan.selfServe) return null;
  return deepFreeze({
    buyerScope: "business",
    priceMode: "configured",
    amountLabel: plan.amountLabel,
    amountCents: plan.amountCents,
    currency: plan.currency,
    billingInterval: plan.billingInterval,
    billingIntervalCount: plan.billingIntervalCount,
    taxBehavior: plan.taxBehavior,
    taxDisplay: plan.taxDisplay,
    selfServe: true,
    stripePriceEnv: plan.stripePriceEnv,
    intendedBuyer: plan.intendedBuyer
  });
}

export function selfServeRunrailOffers(buyerScope = "business") {
  return RUNRAIL_PLAN_CATALOG
    .map((plan) => ({ plan, offer: runrailOfferForPlan(plan, buyerScope) }))
    .filter(({ offer }) => Boolean(offer));
}

export function runrailPlanHasFeature(planOrCode, feature) {
  const plan = typeof planOrCode === "string" ? runrailPlanForCode(planOrCode) : planOrCode;
  return Boolean(plan?.features?.includes(String(feature || "").trim()));
}
