"""
CV6 AI Trading Bot — Educational PPT Generator
Run: python generate_cv6_ppt.py
Requires: pip install python-pptx
Output: CV6_Bot_Education_Guide.pptx
"""

try:
    from pptx import Presentation
    from pptx.util import Inches, Pt, Emu
    from pptx.dml.color import RGBColor
    from pptx.enum.text import PP_ALIGN
    from pptx.util import Inches, Pt
    import os
except ImportError:
    import subprocess, sys
    print("Installing python-pptx...")
    subprocess.check_call([sys.executable, "-m", "pip", "install", "python-pptx", "--break-system-packages"])
    from pptx import Presentation
    from pptx.util import Inches, Pt, Emu
    from pptx.dml.color import RGBColor
    from pptx.enum.text import PP_ALIGN

from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RGBColor
from pptx.enum.text import PP_ALIGN

def rgb(hex_str):
    h = hex_str.lstrip('#')
    return RGBColor(int(h[0:2],16), int(h[2:4],16), int(h[4:6],16))

# Colors
BG      = "0A0F1E"
PANEL   = "0F172A"
CARD    = "1E293B"
BLUE    = "3B82F6"
BLUE_LT = "60A5FA"
GREEN   = "10B981"
YELLOW  = "F59E0B"
PURPLE  = "8B5CF6"
RED     = "EF4444"
TEAL    = "06B6D4"
ORANGE  = "F97316"
WHITE   = "FFFFFF"
TEXT    = "E2E8F0"
MUTED   = "94A3B8"

prs = Presentation()
prs.slide_width  = Inches(13.33)
prs.slide_height = Inches(7.5)

blank_layout = prs.slide_layouts[6]  # completely blank

def add_slide():
    s = prs.slides.add_slide(blank_layout)
    bg = s.background.fill
    bg.solid()
    bg.fore_color.rgb = rgb(BG)
    return s

def add_rect(slide, left, top, width, height, fill_color, alpha=None):
    from pptx.util import Inches
    shape = slide.shapes.add_shape(
        1,  # MSO_SHAPE_TYPE.RECTANGLE
        Inches(left), Inches(top), Inches(width), Inches(height)
    )
    shape.fill.solid()
    shape.fill.fore_color.rgb = rgb(fill_color)
    shape.line.fill.background()
    return shape

def add_text(slide, text, left, top, width, height, font_size=12, bold=False,
             color=WHITE, align="left", wrap=True, italic=False):
    from pptx.util import Inches, Pt
    from pptx.enum.text import PP_ALIGN
    txBox = slide.shapes.add_textbox(Inches(left), Inches(top), Inches(width), Inches(height))
    tf = txBox.text_frame
    tf.word_wrap = wrap
    p = tf.paragraphs[0]
    p.alignment = PP_ALIGN.LEFT if align=="left" else PP_ALIGN.CENTER if align=="center" else PP_ALIGN.RIGHT
    run = p.add_run()
    run.text = text
    run.font.size = Pt(font_size)
    run.font.bold = bold
    run.font.italic = italic
    run.font.color.rgb = rgb(color)
    run.font.name = "Calibri"
    return txBox

# ─── SLIDE 1: Title ───────────────────────────────────────────────────────────
s1 = add_slide()
add_rect(s1, 0, 6.9, 13.33, 0.6, "1E3A5F")
add_text(s1, "CV6 AI TRADING BOT", 0.6, 0.7, 11, 0.8, 14, True, BLUE_LT, "left")
add_text(s1, "How It Works", 0.6, 1.5, 10, 1.6, 56, True, WHITE, "left")
add_text(s1, "Complete Education Guide — Architecture, Flow & Execution",
         0.6, 3.2, 11, 0.6, 16, False, MUTED, "left")
add_text(s1, "For Educational Use  •  CV6 AI Trading OS v1.0  •  FastAPI + React + AI Consensus",
         0.6, 6.95, 12, 0.5, 11, False, MUTED, "left")

# ─── SLIDE 2: What is CV6? ────────────────────────────────────────────────────
s2 = add_slide()
add_text(s2, "What is CV6?", 0.5, 0.25, 12, 0.8, 34, True, WHITE, "left")
add_text(s2, "CV6 is NOT a manual trading app. It is a fully autonomous AI Trading Operating System.",
         0.5, 1.0, 12, 0.5, 14, False, MUTED, "left")

cards = [
    ("Autonomous",    "Scans markets, picks stocks, places orders, monitors positions — all without human input.", BLUE),
    ("AI-Powered",    "Uses GPT, Claude, Gemini & DeepSeek AI models for consensus-based decisions.", GREEN),
    ("Risk-Protected","Built-in kill switch, loss limits, VIX filter, circuit filter, drawdown cap.", YELLOW),
    ("Self-Learning", "Records every trade, analyzes patterns, finds best strategies and AI models.", PURPLE),
    ("Multi-Style",   "Intraday, Swing, F&O, Scalping, Long Term — each with independent capital pool.", TEAL),
    ("Multi-Broker",  "Routes orders to: Angel One, AliceBlue, Upstox, Zerodha, mStock per style.", ORANGE),
]
for i, (title, body, col) in enumerate(cards):
    cx = 0.4 + (i%3) * 4.35
    cy = 1.7 + (i//3) * 2.3
    add_rect(s2, cx, cy, 4.1, 2.0, CARD)
    add_rect(s2, cx, cy, 4.1, 0.45, col)
    add_text(s2, title, cx+0.1, cy+0.06, 3.9, 0.35, 12, True, WHITE, "left")
    add_text(s2, body,  cx+0.1, cy+0.52, 3.9, 1.35, 10, False, TEXT, "left")

# ─── SLIDE 3: System Architecture ────────────────────────────────────────────
s3 = add_slide()
add_text(s3, "System Architecture", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s3, "Three layers: Frontend (React) → Backend (FastAPI) → Market (Brokers & Exchange)",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

layers = [
    ("FRONTEND — React 18 + TypeScript  |  localhost:3000",
     "Dashboard  •  Market Watch  •  Autonomous OS  •  F&O Engine  •  AI Learning  •  Risk Manager  •  Trade Journal  •  Charts  •  Portfolio  •  Settings",
     "1A3A5C", BLUE_LT),
    ("BACKEND — FastAPI + SQLite  |  localhost:8000",
     "autonomous_engine  •  smart_scanner  •  ai_consensus  •  risk_guard  •  fno_engine  •  learning_service  •  broker_allocator  •  capital_pool  •  position_monitor  •  history_service  •  dashboard_service",
     "1A2A3A", TEAL),
    ("MARKET — NSE / BSE / NFO Exchange  |  via Broker APIs",
     "Angel One  •  AliceBlue  •  Upstox  •  Zerodha  •  Dhan  •  mStock  •  Fyers  •  Shoonya",
     "1A1A2E", YELLOW),
]
for i, (title, body, bg_col, col) in enumerate(layers):
    ly = 1.4 + i * 1.7
    add_rect(s3, 0.3, ly, 12.7, 1.5, bg_col)
    add_text(s3, title, 0.5, ly+0.08, 12, 0.45, 11, True, col, "left")
    add_text(s3, body,  0.5, ly+0.55, 12, 0.85, 9.5, False, TEXT, "left")

# ─── SLIDE 4: 5-Stage Scanner ─────────────────────────────────────────────────
s4 = add_slide()
add_text(s4, "5-Stage Market Scanner — Smart AI Cost Control", 0.5, 0.2, 12, 0.7, 30, True, WHITE, "left")
add_text(s4, "AI is called ONLY for Top 3-5 final candidates. All earlier stages use fast local filters.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

stages = [
    ("Stage 1","FULL UNIVERSE","500+ Symbols","Volume & Price filter\nRemove circuit stocks", BLUE),
    ("Stage 2","TECHNICAL","Top 200","EMA / RSI / MACD\nVWAP / ATR / Volume", TEAL),
    ("Stage 3","QUALITY","Top 20","SuperTrend / Breakout\nSector Strength filter", GREEN),
    ("Stage 4","RISK FILTER","Top 5","Circuit / VIX / News\nSector Concentration", YELLOW),
    ("Stage 5","AI CONSENSUS","Top 1-3","GPT + Claude + Gemini\nDeepSeek + AI Cache", PURPLE),
]
for i, (stage, label, count, detail, col) in enumerate(stages):
    bx = 0.3 + i * 2.55
    add_rect(s4, bx, 1.5, 2.35, 4.5, col)
    add_text(s4, stage,  bx+0.1, 1.6,  2.15, 0.35, 9,  True,  WHITE, "center")
    add_text(s4, label,  bx+0.1, 2.05, 2.15, 0.5,  13, True,  WHITE, "center")
    add_text(s4, count,  bx+0.1, 2.65, 2.15, 0.4,  18, True,  WHITE, "center")
    add_text(s4, detail, bx+0.1, 3.15, 2.15, 1.5,  10, False, TEXT,  "center")

add_rect(s4, 0.3, 6.2, 12.7, 0.7, CARD)
add_text(s4, "💡 AI Cache: If a stock was analyzed within TTL (5 min), cached result is reused — ZERO extra AI cost.",
         0.5, 6.28, 12.3, 0.55, 11, False, TEXT, "left")

# ─── SLIDE 5: AI Consensus Engine ────────────────────────────────────────────
s5 = add_slide()
add_text(s5, "AI Consensus Engine", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s5, "Multiple AI models vote on each trade. Majority consensus required before BUY or SELL.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

add_rect(s5, 0.3, 1.4, 4.5, 5.5, CARD)
add_text(s5, "AI Models Used", 0.4, 1.5, 4.3, 0.5, 14, True, GREEN, "left")
models = [("GPT-4o","OpenAI",GREEN), ("Claude 3.5","Anthropic",BLUE_LT),
          ("Gemini Pro","Google",YELLOW), ("DeepSeek","DeepSeek AI",PURPLE),
          ("Ollama / Llama","Local Offline",TEAL)]
for i, (name, company, col) in enumerate(models):
    my = 2.1 + i*0.85
    add_rect(s5, 0.4, my, 4.3, 0.68, col)
    add_text(s5, name,    0.55, my+0.1,  2.2, 0.45, 13, True,  WHITE, "left")
    add_text(s5, company, 2.8,  my+0.14, 1.8, 0.38, 10, False, MUTED, "right")

add_rect(s5, 5.1, 1.4, 3.8, 5.5, "112233")
add_text(s5, "Consensus Logic", 5.2, 1.55, 3.6, 0.55, 14, True, BLUE_LT, "center")
configs = [("1 of N","Fast — risky"), ("2 of N","Standard"), ("3 of N","Confident"), ("All Models","Safest")]
for i, (mode, desc) in enumerate(configs):
    cy = 2.25 + i*0.9
    add_rect(s5, 5.25, cy, 3.5, 0.7, BLUE if i==1 else CARD)
    add_text(s5, mode, 5.25, cy+0.06, 3.5, 0.35, 14, True, WHITE, "center")
    add_text(s5, desc, 5.25, cy+0.4,  3.5, 0.28, 9,  False, MUTED, "center")

add_rect(s5, 9.2, 1.4, 3.9, 5.5, CARD)
add_text(s5, "Decision", 9.3, 1.55, 3.7, 0.5, 14, True, WHITE, "center")
decisions = [("BUY",GREEN),("SELL",RED),("HOLD",YELLOW),("REJECT",MUTED)]
for i, (d, col) in enumerate(decisions):
    dy = 2.2 + i*1.05
    add_rect(s5, 9.3, dy, 3.7, 0.8, col)
    add_text(s5, d, 9.3, dy+0.1, 3.7, 0.58, 22, True, WHITE, "center")

# ─── SLIDE 6: Risk Guard ─────────────────────────────────────────────────────
s6 = add_slide()
add_text(s6, "Risk Guard — 8-Layer Protection", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s6, "Every trade passes ALL 8 layers. If ANY layer blocks, the trade is REJECTED.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

risk_layers = [
    ("1","Kill Switch",    "Emergency stop. Blocks ALL trades instantly. Manual ON/OFF.",       RED),
    ("2","Daily Loss Limit","Stops when daily P&L loss hits threshold (e.g. ₹2,000/day).",   ORANGE),
    ("3","Weekly Loss",    "Rolling 7-day loss tracking with automatic block.",                YELLOW),
    ("4","Monthly Loss",   "Rolling 30-day loss tracking with automatic block.",               YELLOW),
    ("5","Max Drawdown",   "Stops trading when portfolio drops by % from its peak.",           BLUE),
    ("6","Market Hours",   "Only trades 09:15 to 15:15 IST. No after-hours orders.",          TEAL),
    ("7","VIX Filter",     "Pauses when India VIX > 22 (high volatility = danger).",          PURPLE),
    ("8","Sector Limit",   "Max 30% of deployed capital in any single sector.",               GREEN),
]
for i, (n, name, desc, col) in enumerate(risk_layers):
    col_idx = i % 2
    row_idx = i // 2
    bx = 0.3 + col_idx * 6.6
    by = 1.4 + row_idx * 1.42
    add_rect(s6, bx, by, 6.3, 1.25, CARD)
    add_rect(s6, bx, by, 0.55, 1.25, col)
    add_text(s6, n,    bx+0.08, by+0.4,  0.4, 0.45, 16, True, WHITE,  "center")
    add_text(s6, name, bx+0.65, by+0.08, 5.5, 0.42, 13, True, col,    "left")
    add_text(s6, desc, bx+0.65, by+0.55, 5.5, 0.6,  10, False, MUTED, "left")

# ─── SLIDE 7: Capital Pools ────────────────────────────────────────────────────
s7 = add_slide()
add_text(s7, "Capital Pool System", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s7, "5 independent pools. Losses in one pool NEVER affect others. Each has own broker & P&L.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

add_rect(s7, 4.5, 1.4, 4.3, 0.65, BLUE)
add_text(s7, "TOTAL CAPITAL  (e.g. ₹1,00,000)", 4.5, 1.4, 4.3, 0.65, 12, True, WHITE, "center")

pools = [
    ("INTRADAY","30%","Angel One", BLUE),
    ("SWING",   "25%","AliceBlue", GREEN),
    ("F&O",     "20%","Upstox",    PURPLE),
    ("SCALPING","10%","Angel One", YELLOW),
    ("LONG TERM","15%","Zerodha",   TEAL),
]
for i, (name, pct, broker, col) in enumerate(pools):
    px = 0.4 + i * 2.55
    add_rect(s7, px, 2.4, 2.35, 4.5, CARD)
    add_rect(s7, px, 2.4, 2.35, 0.45, col)
    add_text(s7, name,   px+0.1, 2.46, 2.15, 0.35, 10, True,  WHITE, "center")
    add_text(s7, pct,    px+0.1, 3.0,  2.15, 0.75, 30, True,  WHITE, "center")
    add_text(s7, "of capital", px+0.1, 3.75, 2.15, 0.3, 9, False, MUTED, "center")
    add_text(s7, "Broker:", px+0.1, 4.15, 2.15, 0.3, 9, False, MUTED, "center")
    add_text(s7, broker,  px+0.1, 4.45, 2.15, 0.35, 11, True, col, "center")
    add_text(s7, "• Own P&L\n• Own Positions\n• Own Risk", px+0.1, 4.9, 2.15, 0.9, 8.5, False, MUTED, "left")

# ─── SLIDE 8: Order Execution Flow ────────────────────────────────────────────
s8 = add_slide()
add_text(s8, "Order Execution Flow", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s8, "From AI decision → Broker API → NSE/BSE Exchange in seconds",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

steps = [
    ("1","AI Decides","Confidence > 60%\nBUY or SELL signal",    BLUE),
    ("2","Risk Check","All 8 layers pass\nKill switch OFF",       YELLOW),
    ("3","Position Size","Qty / SL / Target\nCapital × Risk %",  GREEN),
    ("4","Broker Route","Style → Broker\nExchange & Product",    PURPLE),
    ("5","Order Sent","PAPER=Simulated\nREAL=Broker API",        ORANGE),
]
for i, (n, title, detail, col) in enumerate(steps):
    bx = 0.4 + i * 2.55
    add_rect(s8, bx, 1.4, 2.35, 2.8, CARD)
    add_rect(s8, bx+0.85, 1.48, 0.65, 0.65, col)
    add_text(s8, n,      bx+0.85, 1.48, 0.65, 0.65, 18, True, WHITE, "center")
    add_text(s8, title,  bx+0.1,  2.25, 2.15, 0.55, 12, True, col,   "center")
    add_text(s8, detail, bx+0.1,  2.85, 2.15, 1.25, 10, False, MUTED,"center")

add_rect(s8, 0.3, 4.45, 12.7, 1.8, "1a0a0a")
add_text(s8, "NSE / BSE / NFO Exchange — Results", 0.5, 4.55, 12, 0.45, 14, True, RED, "left")
results = [("✅ Accepted","Order filled at market price",GREEN),
           ("❌ Rejected","Broker RMS / margin issue",RED),
           ("⚡ Partial Fill","Partial qty → track remainder",YELLOW),
           ("✔ Complete","Full qty filled → Position open",TEAL)]
for i, (r, d, c) in enumerate(results):
    rx = 0.5 + i * 3.2
    add_text(s8, r, rx, 5.1,  3.0, 0.38, 11, True,  c,    "left")
    add_text(s8, d, rx, 5.5,  3.0, 0.55, 9,  False, MUTED, "left")

# ─── SLIDE 9: Position Monitor ────────────────────────────────────────────────
s9 = add_slide()
add_text(s9, "Position Monitor Engine", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s9, "Runs every cycle. Checks every open position. Closes when any exit condition is met.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

exits = [
    ("Target Hit",    "LTP reaches target price → CLOSE at profit",        GREEN),
    ("Stop Loss",     "LTP hits trailing SL → CLOSE at small loss",         RED),
    ("Trailing SL",   "SL moves up as price rises (0.5% step). Locks profit.", BLUE),
    ("EOD Square-off","3:10 PM → Auto-close INTRADAY + SCALPING positions",YELLOW),
    ("AI Re-exit",    "Swing: AI re-analyzes → if REVERSE signal → CLOSE", PURPLE),
    ("Risk Exit",     "Kill switch or loss limit hit → ALL positions close",ORANGE),
]
for i, (title, desc, col) in enumerate(exits):
    col_n = i % 3
    row_n = i // 3
    bx = 0.3 + col_n * 4.35
    by = 1.4 + row_n * 2.6
    add_rect(s9, bx, by, 4.15, 2.3, CARD)
    add_rect(s9, bx, by, 4.15, 0.5, col)
    add_text(s9, title, bx+0.12, by+0.08, 3.9, 0.38, 13, True, WHITE, "left")
    add_text(s9, desc,  bx+0.12, by+0.6,  3.9, 1.55, 10, False, TEXT, "left")

# ─── SLIDE 10: Learning Engine ────────────────────────────────────────────────
s10 = add_slide()
add_text(s10, "AI Learning Engine", 0.5, 0.2, 12, 0.7, 32, True, WHITE, "left")
add_text(s10, "Every trade is recorded. The bot learns what works and what doesn't — automatically.",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

add_rect(s10, 0.3, 1.4, 5.9, 5.5, CARD)
add_text(s10, "What Gets Recorded Per Trade", 0.5, 1.55, 5.5, 0.5, 14, True, TEAL, "left")
records = ["Symbol, Side (BUY/SELL), Quantity",
           "Entry Price & Exit Price",
           "Stop Loss & Target Price",
           "Strategy (EMA/RSI/SuperTrend...)",
           "AI Models Used + Confidence Score",
           "Broker, Trading Style",
           "P&L in Rupees and Percentage",
           "Time of Entry and Exit",
           "Sector of the Stock",
           "Win / Loss outcome"]
for i, r in enumerate(records):
    add_text(s10, "• " + r, 0.5, 2.15+i*0.41, 5.6, 0.38, 10, False, TEXT, "left")

add_rect(s10, 6.5, 1.4, 6.5, 5.5, CARD)
add_text(s10, "What the Bot Learns", 6.65, 1.55, 6.2, 0.5, 14, True, PURPLE, "left")
learns = [("Best Strategy","EMA vs RSI vs SuperTrend ranking"),
          ("Best AI Model","GPT vs Claude accuracy comparison"),
          ("Best Time","9:15–10:00 AM peak performance"),
          ("Worst Time","12:00–14:00 low performance window"),
          ("Win Rate","% of trades that made profit"),
          ("Profit Factor","Gross profit ÷ Gross loss ratio"),
          ("Sharpe Ratio","Risk-adjusted return score"),
          ("AI Accuracy","How often AI was right"),
          ("Suggestions","Auto tips to improve performance")]
for i, (metric, val) in enumerate(learns):
    my = 2.15 + i*0.52
    add_text(s10, metric + ":", 6.65, my, 2.8, 0.4, 10, True, MUTED, "left")
    add_text(s10, val,          9.5,  my, 3.3, 0.4, 10, False, TEXT, "left")

# ─── SLIDE 11: How to Use ─────────────────────────────────────────────────────
s11 = add_slide()
add_text(s11, "How to Start Trading with CV6", 0.5, 0.2, 12, 0.7, 30, True, WHITE, "left")
add_text(s11, "Step-by-step from first login to first autonomous trade",
         0.5, 0.9, 12, 0.4, 13, False, MUTED, "left")

setup_steps = [
    ("01","Start Backend",    "Run: python main.py → Backend on localhost:8000", BLUE),
    ("02","Start Frontend",   "Run: npm run dev → App on localhost:3000. Login.", TEAL),
    ("03","Connect Broker",   "Settings → Brokers → Enter API key → Click Connect", GREEN),
    ("04","Set AI Keys",      "Settings → AI Models → Enter OpenAI / Anthropic keys", PURPLE),
    ("05","Configure Capital","Autonomous OS → Set capital, allocation %, risk %", YELLOW),
    ("06","Set Risk Limits",  "Risk Controls → Daily/weekly loss, VIX threshold, filters ON", ORANGE),
    ("07","Choose PAPER Mode","Mode → PAPER first. Test with no real money.", RED),
    ("08","Start the Engine", "Click START → Bot scans NSE every 30 seconds auto.", GREEN),
]
for i, (n, title, desc, col) in enumerate(setup_steps):
    col_n = i % 2
    row_n = i // 2
    bx = 0.3 + col_n * 6.6
    by = 1.4 + row_n * 1.42
    add_rect(s11, bx, by, 6.3, 1.25, CARD)
    add_rect(s11, bx, by, 0.65, 1.25, col)
    add_text(s11, n,     bx+0.08, by+0.38, 0.5, 0.5, 14, True, WHITE, "center")
    add_text(s11, title, bx+0.75, by+0.08, 5.4, 0.42, 13, True,  col,  "left")
    add_text(s11, desc,  bx+0.75, by+0.55, 5.4, 0.6,  10, False, MUTED,"left")

# ─── SLIDE 12: Complete Flow Summary ─────────────────────────────────────────
s12 = add_slide()
add_text(s12, "Complete Bot Cycle — 10 Steps Every 30 Seconds", 0.5, 0.2, 12, 0.7, 28, True, WHITE, "left")
add_text(s12, "Runs continuously during market hours 09:15–15:15 IST",
         0.5, 0.88, 12, 0.38, 12, False, MUTED, "left")

flow = [
    ("1","SCAN",    BLUE),
    ("2","FILTER",  TEAL),
    ("3","RISK",    YELLOW),
    ("4","AI",      GREEN),
    ("5","DECIDE",  PURPLE),
    ("6","SIZE",    ORANGE),
    ("7","ROUTE",   BLUE_LT),
    ("8","ORDER",   RED),
    ("9","MONITOR", TEAL),
    ("10","LEARN",  PURPLE),
]
for i, (n, label, col) in enumerate(flow):
    bx = 0.25 + i * 1.29
    bh = 1.8 + i * 0.18
    by = 6.6 - bh
    add_rect(s12, bx, by, 1.2, bh, col)
    add_text(s12, n,     bx, by+0.06, 1.2, 0.35, 10, True, WHITE, "center")
    add_text(s12, label, bx, by+bh+0.04, 1.2, 0.32, 8, True, col, "center")

add_text(s12, "↩  After Step 10 → Back to Step 1 (Next Scan Cycle)",
         2, 1.38, 9, 0.42, 12, False, MUTED, "center")

# ─── SLIDE 13: Key Takeaways ──────────────────────────────────────────────────
s13 = add_slide()
add_rect(s13, 0, 6.7, 13.33, 0.8, "1E3A5F")
add_text(s13, "Key Takeaways", 0.6, 0.5, 11, 0.85, 36, True, WHITE, "left")

takeaways = [
    ("✅","CV6 is FULLY AUTONOMOUS — you only set parameters, the bot does ALL trading.",      GREEN),
    ("🧠","AI Consensus uses 4+ AI models — no single AI makes the final decision alone.",     BLUE_LT),
    ("🛡️","8-Layer Risk Guard protects capital at every step before every single trade.",     YELLOW),
    ("💰","5 Independent Capital Pools — losses in Intraday NEVER affect Swing pool.",        TEAL),
    ("📚","Learning Engine records everything and generates improvement suggestions auto.",    PURPLE),
    ("⚙️","ALWAYS test in PAPER mode first. Switch to REAL only after confident results.",    ORANGE),
]
for i, (icon, text, col) in enumerate(takeaways):
    ty = 1.5 + i * 0.82
    add_rect(s13, 0.4, ty, 12.5, 0.68, CARD)
    add_rect(s13, 0.4, ty, 0.6, 0.68, col)
    add_text(s13, icon, 0.45, ty+0.12, 0.52, 0.44, 14, False, WHITE, "center")
    add_text(s13, text, 1.1, ty+0.1, 11.6, 0.5, 12, False, TEXT, "left")

add_text(s13, "CV6 AI Trading OS  •  FastAPI + React 18 + AI Consensus  •  For Educational Use",
         0.4, 6.78, 12.5, 0.42, 10, False, MUTED, "center")

# ─── SAVE ─────────────────────────────────────────────────────────────────────
output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "CV6_Bot_Education_Guide.pptx")
prs.save(output_path)
print(f"\n✅ DONE! Saved: {output_path}")
print(f"   Slides: 13")
print(f"   Topic: CV6 AI Trading Bot — How It Works")
