export type PerpsLine = {
  key: string;
  label: string;
  color: string;
  yAxisId?: "left" | "right";
};

export type PerpsPlaybook = {
  whatItMeasures: string;
  interpretation: string[];
  tradeExpressions: string[];
  caveats: string[];
  companionChecks: string[];
};

export type PerpsDashboardConfig = {
  id: string;
  title: string;
  description: string;
  family: string;
  dualAxis?: boolean;
  lines: PerpsLine[];
  tableColumns: string[];
  relatedSignals: string[];
  playbook: PerpsPlaybook;
};

export const PERPS_SIGNAL_DESCRIPTIONS: Record<string, string> = {
  carry_score: "Composite score for total perps carry richness and crowding.",
  cascade_risk_score: "Composite score for liquidation fragility and OI concentration.",
  toxicity_score: "Composite adverse-selection and toxic-flow score.",
  positioning_score: "Composite leverage build-up and OI-price divergence score.",
  fragility_score: "Composite spread, depth, and venue-dislocation fragility score.",
};

export const PERPS_DASHBOARDS: PerpsDashboardConfig[] = [
  {
    id: "funding_basis_carry",
    title: "Funding-Basis Carry",
    description: "Total carry economics across spot-perp basis, hourly funding, and carry momentum.",
    family: "carry",
    dualAxis: true,
    lines: [
      { key: "carry_annualized_pct", label: "Carry Ann %", color: "#6ac2ff", yAxisId: "left" },
      { key: "carry_zscore_7d", label: "Carry Z 7D", color: "#ffd166", yAxisId: "right" },
      { key: "carry_momentum_1h", label: "Carry Mom 1H", color: "#f58549", yAxisId: "right" },
      { key: "cross_venue_funding_spread", label: "Funding Spread", color: "#8dd3c7", yAxisId: "right" },
    ],
    tableColumns: ["ts", "basis_bps", "funding_rate_1h", "carry_annualized_pct", "carry_zscore_7d", "carry_momentum_24h", "quality_flag"],
    relatedSignals: ["carry_score", "positioning_score"],
    playbook: {
      whatItMeasures: "This combines spot-perp basis with hourly funding into the actual cost or reward of holding a perp position.",
      interpretation: [
        "High positive carry usually means longs are paying to stay crowded. Extreme carry often precedes squeezes when the position becomes too expensive to maintain.",
        "Carry momentum matters as much as level. A rich but decelerating carry regime is different from one still steepening.",
        "Cross-venue funding spread shows whether crowding is concentrated on one venue or spread across the whole market.",
      ],
      tradeExpressions: [
        "Use rich and decelerating carry as a setup to look for squeeze reversals rather than chase continuation.",
        "Use cheap or negative carry to screen for cleaner directional perp entries where positioning is not already crowded.",
      ],
      caveats: [
        "Carry can stay rich for longer than expected in persistent bull regimes.",
        "Basis can be temporarily distorted around exchange-specific inventory pressure.",
      ],
      companionChecks: ["Liquidation Cascade", "OI-Price Divergence", "Volatility Microstructure"],
    },
  },
  {
    id: "liquidation_cascade",
    title: "Liquidation Cascade Risk",
    description: "Liquidation intensity, asymmetry, and OI concentration versus available depth.",
    family: "stress",
    lines: [
      { key: "cascade_risk_score", label: "Cascade Risk", color: "#6ac2ff" },
      { key: "liq_intensity_zscore", label: "Liq Intensity Z", color: "#ffd166" },
      { key: "liq_asymmetry", label: "Liq Asymmetry", color: "#f58549" },
      { key: "oi_concentration", label: "OI Concentration", color: "#8dd3c7" },
    ],
    tableColumns: ["ts", "long_liq_notional", "short_liq_notional", "liq_intensity_zscore", "oi_concentration", "cascade_regime", "quality_flag"],
    relatedSignals: ["cascade_risk_score", "fragility_score"],
    playbook: {
      whatItMeasures: "This estimates whether the market has the leverage crowding and liquidation pressure needed for a cascade.",
      interpretation: [
        "High OI relative to near-book depth means the market is fragile even before liquidations actually accelerate.",
        "Strong one-sided asymmetry in liquidation flow tells you which side is already being forced out.",
        "Rising liquidation intensity on top of already rich carry is the classic pre-cascade setup.",
      ],
      tradeExpressions: [
        "Use a rising cascade-risk regime to avoid fading strong moves too early.",
        "Use asymmetric liquidation spikes to identify likely continuation direction or exhaustion depending on whether crowding is still elevated.",
      ],
      caveats: [
        "Exchange liquidation feeds are noisy and venue-specific.",
        "A high score is a precondition signal, not a precise timing tool.",
      ],
      companionChecks: ["Funding-Basis Carry", "Depth Resilience", "OI-Price Divergence"],
    },
  },
  {
    id: "order_flow_toxicity",
    title: "Order Flow Toxicity",
    description: "VPIN-style toxic flow, OFI persistence, and concentration of large aggressive prints.",
    family: "flow",
    lines: [
      { key: "vpin_50", label: "VPIN 50", color: "#6ac2ff" },
      { key: "toxic_flow_zscore_4h", label: "Toxic Z 4H", color: "#ffd166" },
      { key: "ofi_persistence", label: "OFI Persist", color: "#f58549" },
      { key: "large_trade_ratio", label: "Large Trade Ratio", color: "#8dd3c7" },
    ],
    tableColumns: ["ts", "vpin_50", "toxic_flow_zscore_4h", "toxic_flow_zscore_24h", "ofi_persistence", "large_trade_ratio", "toxicity_regime"],
    relatedSignals: ["toxicity_score", "fragility_score"],
    playbook: {
      whatItMeasures: "This estimates whether aggressive flow is informed and toxic enough to make market makers pull back.",
      interpretation: [
        "High VPIN with persistent OFI means directional flow is not just large, it is sustained.",
        "A rising large-trade ratio often indicates that a small set of informed participants is dominating the tape.",
        "Toxic flow and widening spread together usually mean adverse selection is rising quickly.",
      ],
      tradeExpressions: [
        "Use toxicity spikes to avoid mean-reversion trades when the tape is becoming informational.",
        "Use falling toxicity after an event to identify when conditions are normalizing again.",
      ],
      caveats: [
        "VPIN-style measures are proxies, not true informed-trading probabilities.",
        "Low-liquidity hours can look toxic simply because the tape is sparse.",
      ],
      companionChecks: ["Depth Resilience", "Volatility Microstructure", "Cross-Venue Price Discovery"],
    },
  },
  {
    id: "oi_price_divergence",
    title: "OI-Price Divergence",
    description: "Leverage build-up and unwind pressure separated from pure price direction.",
    family: "positioning",
    lines: [
      { key: "oi_change_1h", label: "OI Δ 1H %", color: "#6ac2ff" },
      { key: "price_change_1h", label: "Price Δ 1H bps", color: "#ffd166" },
      { key: "oi_price_divergence", label: "OI/Price Div", color: "#f58549" },
      { key: "oi_acceleration", label: "OI Accel", color: "#8dd3c7" },
    ],
    tableColumns: ["ts", "oi_change_1h", "oi_change_4h", "oi_change_24h", "price_change_1h", "oi_price_divergence", "leverage_regime"],
    relatedSignals: ["positioning_score", "carry_score"],
    playbook: {
      whatItMeasures: "This shows whether leverage is being added or removed independently of what price alone suggests.",
      interpretation: [
        "OI rising with muted price often means hidden leverage is building.",
        "OI falling into a move often means forced unwind rather than fresh conviction.",
        "Acceleration matters because sudden leverage build-up tends to break rather than drift.",
      ],
      tradeExpressions: [
        "Use rising divergence and acceleration as a warning that a clean-looking trend may actually be crowding.",
        "Use unwind states to distinguish organic trend moves from leverage flushes that may overshoot.",
      ],
      caveats: [
        "OI updates are venue-specific and can lag slightly.",
        "A divergence signal needs carry or liquidation context to become actionable.",
      ],
      companionChecks: ["Funding-Basis Carry", "Liquidation Cascade", "Cumulative Delta Momentum"],
    },
  },
  {
    id: "cross_venue_price_discovery",
    title: "Cross-Venue Price Discovery",
    description: "Lead-lag, venue dislocations, and convergence speed across Binance and Bybit.",
    family: "cross_venue",
    lines: [
      { key: "lead_lag_score", label: "Lead-Lag", color: "#6ac2ff" },
      { key: "venue_dislocation_bps", label: "Dislocation bps", color: "#ffd166" },
      { key: "convergence_half_life_secs", label: "Half-Life", color: "#f58549" },
    ],
    tableColumns: ["ts", "lead_lag_score", "venue_dislocation_bps", "convergence_half_life_secs", "price_discovery_leader", "quality_flag"],
    relatedSignals: ["fragility_score", "toxicity_score"],
    playbook: {
      whatItMeasures: "This identifies which venue is leading and how tightly Binance and Bybit are coupling or decoupling.",
      interpretation: [
        "A stable leader matters because that venue often sees informed flow first.",
        "Large dislocations with slow convergence imply market stress or one-venue inventory pressure.",
        "Fast convergence means dislocations are mostly noise; slow convergence makes them information.",
      ],
      tradeExpressions: [
        "Use the leader venue as the primary confirmation feed during fast markets.",
        "Treat persistent cross-venue dislocation as a stress signal rather than a clean arb signal unless the convergence speed improves.",
      ],
      caveats: [
        "This is a reduced-form lead-lag proxy, not a full information-share model.",
        "Sparse one-minute windows can make leader changes look noisier than they are.",
      ],
      companionChecks: ["Order Flow Toxicity", "Depth Resilience"],
    },
  },
  {
    id: "depth_resilience",
    title: "Depth Resilience",
    description: "Spread regime, refill speed, and book fragility after aggressive flow shocks.",
    family: "liquidity",
    lines: [
      { key: "depth_recovery_speed", label: "Recovery Speed", color: "#6ac2ff" },
      { key: "spread_zscore_4h", label: "Spread Z 4H", color: "#ffd166" },
      { key: "spread_zscore_24h", label: "Spread Z 24H", color: "#f58549" },
      { key: "depth_imbalance_momentum", label: "Imb Mom", color: "#8dd3c7" },
    ],
    tableColumns: ["ts", "depth_recovery_speed", "spread_bps", "spread_zscore_4h", "spread_zscore_24h", "spread_regime", "quality_flag"],
    relatedSignals: ["fragility_score", "cascade_risk_score"],
    playbook: {
      whatItMeasures: "This estimates how quickly the book refills after aggressive flow and whether spreads are moving into a stress regime.",
      interpretation: [
        "Low recovery speed means the market is fragile: once depth is consumed, it does not come back quickly.",
        "Spread z-scores tell you whether the current quote environment is normal or stressed relative to itself.",
        "A widening spread with worsening imbalance momentum often precedes short-term vol expansion.",
      ],
      tradeExpressions: [
        "Use low resilience as a condition for wider stop placement or no-trade decisions.",
        "When resilience improves after a stress burst, it often marks the first sign of normalization.",
      ],
      caveats: [
        "Recovery speed is a proxy and depends on the chosen bar interval.",
        "Venue outages or feed lag can mimic low resilience.",
      ],
      companionChecks: ["Order Flow Toxicity", "Liquidation Cascade", "Volatility Microstructure"],
    },
  },
  {
    id: "vol_microstructure",
    title: "Volatility Microstructure",
    description: "Multi-frequency realized vol, signature ratio, and vol clustering.",
    family: "volatility",
    lines: [
      { key: "rv_5s", label: "RV 5S", color: "#6ac2ff" },
      { key: "rv_1m", label: "RV 1M", color: "#ffd166" },
      { key: "rv_5m", label: "RV 5M", color: "#f58549" },
      { key: "vol_signature_ratio", label: "Signature Ratio", color: "#8dd3c7" },
    ],
    tableColumns: ["ts", "rv_5s", "rv_1m", "rv_5m", "vol_signature_ratio", "vol_clustering", "rv_regime"],
    relatedSignals: ["fragility_score", "carry_score"],
    playbook: {
      whatItMeasures: "This separates noisy microstructure chop from true short-horizon trend behavior by comparing realized vol across frequencies.",
      interpretation: [
        "A high signature ratio usually means lots of microstructure noise relative to slower trend vol.",
        "A lower ratio with rising clustering often means the tape is moving from noise into persistent directional activity.",
        "This is the regime selector for deciding whether short-horizon signals should be faded or followed.",
      ],
      tradeExpressions: [
        "Favor mean-reversion tactics when the signature ratio is high and clustering is low.",
        "Favor momentum-style bias when clustering is high and the ratio is no longer noise-dominated.",
      ],
      caveats: [
        "Sampling frequency matters; these are only comparable within the same implementation.",
      ],
      companionChecks: ["Order Flow Toxicity", "Depth Resilience"],
    },
  },
  {
    id: "cum_delta_momentum",
    title: "Cumulative Delta Momentum",
    description: "Delta acceleration, absorption, and divergence between aggressive flow and price.",
    family: "flow",
    lines: [
      { key: "cum_delta_acceleration", label: "Delta Accel", color: "#6ac2ff" },
      { key: "delta_divergence", label: "Delta Divergence", color: "#ffd166" },
      { key: "absorption_ratio", label: "Absorption", color: "#f58549" },
    ],
    tableColumns: ["ts", "cum_delta_acceleration", "delta_divergence", "absorption_ratio", "delta_regime", "quality_flag"],
    relatedSignals: ["positioning_score", "toxicity_score"],
    playbook: {
      whatItMeasures: "This tracks whether aggressive buy/sell pressure is intensifying, being absorbed, or failing to move price.",
      interpretation: [
        "Strong delta acceleration with low absorption means flow is moving price cleanly.",
        "Strong delta acceleration with high absorption means the market is leaning hard but getting met by passive liquidity.",
        "Divergence between delta and price often marks exhaustion or stealth accumulation/distribution.",
      ],
      tradeExpressions: [
        "Use absorbed aggressive flow to screen for fade setups once other stress measures stop worsening.",
        "Use aligned delta acceleration and price response to confirm continuation setups.",
      ],
      caveats: [
        "Absorption is a proxy based on trade notional versus price response, not a full queue-reconstruction measure.",
      ],
      companionChecks: ["OI-Price Divergence", "Order Flow Toxicity"],
    },
  },
];
