#!/usr/bin/env python3
"""
AI-Adjusted DCF Valuation Analysis for MSFT, AMZN, GOOGL
Factoring in Chatbot Advertising Revenue Streams
March 31, 2026
"""

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
from docx import Document
from docx.shared import Inches, Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
import os

OUT_DIR = "/Users/joemac/.openclaw/workspace/projects/investing"

# ============================================================
# DCF MODEL
# ============================================================

def dcf_intrinsic_value(fcf_base, g1, g2, discount=0.10, terminal_g=0.03, years_phase1=5, years_total=10, shares_b=1.0):
    """Two-stage DCF model. Returns intrinsic value per share."""
    fcfs = []
    fcf = fcf_base
    for y in range(1, years_total + 1):
        g = g1 if y <= years_phase1 else g2
        fcf = fcf * (1 + g)
        pv = fcf / (1 + discount) ** y
        fcfs.append(pv)
    # Terminal value
    terminal_fcf = fcf * (1 + terminal_g)
    terminal_value = terminal_fcf / (discount - terminal_g)
    pv_terminal = terminal_value / (1 + discount) ** years_total
    total = sum(fcfs) + pv_terminal
    return round(total / shares_b, 2)


# ============================================================
# COMPANY DATA WITH AI-ADJUSTED ASSUMPTIONS
# ============================================================

companies = {
    'MSFT': {
        'name': 'MICROSOFT',
        'ticker': 'MSFT',
        'price': 364.78,
        'shares': 7.43,  # billions
        'fcf': 70,  # $B
        'revenue': 282,  # $B
        'scenarios': {
            'Conservative': (0.12, 0.08),
            'Medium':       (0.16, 0.11),
            'Optimistic':   (0.20, 0.14),
        },
        # Revenue breakdown current (2025) in $B
        'rev_current': {
            'Cloud (Azure)': 105,
            'Office/Productivity': 70,
            'Windows/Devices': 35,
            'LinkedIn': 20,
            'Gaming': 25,
            'OpenAI Rev Share': 2,
            'Other': 25,
        },
        # Projected 2030 revenue in $B (medium scenario)
        'rev_2030': {
            'Cloud (Azure + AI)': 210,
            'Office/Copilot': 105,
            'Windows/Devices': 30,
            'LinkedIn': 28,
            'Gaming': 30,
            'OpenAI Rev Share': 15,
            'Other': 32,
        },
    },
    'AMZN': {
        'name': 'AMAZON',
        'ticker': 'AMZN',
        'price': 206.06,
        'shares': 10.5,
        'fcf': 55,
        'revenue': 638,
        'scenarios': {
            'Conservative': (0.14, 0.09),
            'Medium':       (0.20, 0.13),
            'Optimistic':   (0.26, 0.16),
        },
        'rev_current': {
            'Online Stores': 250,
            'AWS': 115,
            'Advertising': 60,
            'Third-Party Seller': 155,
            'Subscriptions': 45,
            'Other': 13,
        },
        'rev_2030': {
            'Online Stores': 310,
            'AWS (incl AI)': 250,
            'Advertising + AI Ads': 130,
            'Third-Party Seller': 210,
            'Subscriptions': 65,
            'Other': 20,
        },
    },
    'GOOGL': {
        'name': 'ALPHABET',
        'ticker': 'GOOGL',
        'price': 282.10,
        'shares': 12.1,
        'fcf': 73,
        'revenue': 381,
        'scenarios': {
            'Conservative': (0.04, 0.03),
            'Medium':       (0.09, 0.06),
            'Optimistic':   (0.14, 0.10),
        },
        'rev_current': {
            'Search Ads': 210,
            'YouTube': 50,
            'Google Cloud': 45,
            'Network Ads': 35,
            'Subscriptions': 25,
            'Other Bets': 16,
        },
        'rev_2030': {
            'Search + AI Ads': 190,
            'YouTube': 75,
            'Google Cloud (AI)': 110,
            'Network Ads': 25,
            'Gemini Monetization': 30,
            'Subscriptions': 40,
            'Other Bets': 20,
        },
    },
}

# Calculate intrinsic values
results = {}
for ticker, data in companies.items():
    results[ticker] = {}
    for scenario, (g1, g2) in data['scenarios'].items():
        iv = dcf_intrinsic_value(data['fcf'], g1, g2, shares_b=data['shares'])
        mos = round(iv * 0.75, 2)
        results[ticker][scenario] = {'iv': iv, 'mos': mos}
    print(f"\n{data['name']} ({ticker}) — Current Price: ${data['price']}")
    for s in ['Conservative', 'Medium', 'Optimistic']:
        r = results[ticker][s]
        print(f"  {s:15s}: IV=${r['iv']:>8.2f}  |  25% MoS Buy=${r['mos']:>8.2f}")


# ============================================================
# CHART 1: BUY ZONES (matching existing style)
# ============================================================

def create_buy_zones_chart():
    fig, axes = plt.subplots(1, 3, figsize=(18, 9), dpi=200)
    fig.patch.set_facecolor('white')
    
    # Title
    fig.suptitle("AI-ADJUSTED DCF Valuation — Buy Zones with 25% Margin of Safety",
                 fontsize=16, fontweight='bold', y=0.97)
    fig.text(0.5, 0.935, "Updated March 31, 2026  |  Factoring in Chatbot Advertising Revenue Streams  |  10% Discount Rate  |  10-Year Projection",
             ha='center', fontsize=10, color='#555555')
    
    tickers = ['MSFT', 'AMZN', 'GOOGL']
    
    # Color definitions
    colors = {
        'strong_buy': '#c8e6c9',   # light green
        'buy':        '#fff9c4',   # light yellow
        'fair':       '#ffe0b2',   # light orange
        'overvalued': '#ffcdd2',   # light red
    }
    
    for idx, ticker in enumerate(tickers):
        ax = axes[idx]
        data = companies[ticker]
        r = results[ticker]
        
        cons_mos = r['Conservative']['mos']
        med_mos = r['Medium']['mos']
        opt_mos = r['Optimistic']['mos']
        cons_iv = r['Conservative']['iv']
        med_iv = r['Medium']['iv']
        opt_iv = r['Optimistic']['iv']
        price = data['price']
        
        # Dynamic y-axis range
        all_vals = [cons_mos, med_mos, opt_mos, cons_iv, med_iv, opt_iv, price]
        y_min = min(all_vals) * 0.85
        y_max = max(all_vals) * 1.15
        
        ax.set_ylim(y_min, y_max)
        ax.set_xlim(0, 1)
        ax.set_xticks([])
        
        # Background zones
        ax.axhspan(y_min, cons_mos, color=colors['strong_buy'], alpha=0.7)
        ax.axhspan(cons_mos, med_mos, color=colors['buy'], alpha=0.7)
        ax.axhspan(med_mos, opt_mos, color=colors['fair'], alpha=0.7)
        ax.axhspan(opt_mos, y_max, color=colors['overvalued'], alpha=0.5)
        
        # Zone labels
        ax.text(0.5, (y_min + cons_mos) / 2, 'STRONG BUY\nZONE', ha='center', va='center',
                fontsize=9, fontweight='bold', color='#2e7d32', alpha=0.7)
        ax.text(0.5, (cons_mos + med_mos) / 2, 'BUY ZONE', ha='center', va='center',
                fontsize=9, fontweight='bold', color='#f57f17', alpha=0.7)
        ax.text(0.5, (med_mos + opt_mos) / 2, 'FAIR VALUE', ha='center', va='center',
                fontsize=9, fontweight='bold', color='#e65100', alpha=0.7)
        ax.text(0.5, (opt_mos + y_max) / 2, 'OVERVALUED', ha='center', va='center',
                fontsize=9, fontweight='bold', color='#c62828', alpha=0.7)
        
        # Horizontal lines for MoS levels
        ax.axhline(y=cons_mos, color='#4caf50', linewidth=1.5, linestyle='-')
        ax.axhline(y=med_mos, color='#2196f3', linewidth=1.5, linestyle='-')
        ax.axhline(y=opt_mos, color='#ff9800', linewidth=1.5, linestyle='-')
        
        # MoS labels on left
        ax.text(-0.02, cons_mos, f'${cons_mos:.0f}  Conservative', ha='right', va='center',
                fontsize=8, fontweight='bold', color='#4caf50', transform=ax.get_yaxis_transform())
        ax.text(-0.02, med_mos, f'${med_mos:.0f}  Medium', ha='right', va='center',
                fontsize=8, fontweight='bold', color='#2196f3', transform=ax.get_yaxis_transform())
        ax.text(-0.02, opt_mos, f'${opt_mos:.0f}  Optimistic', ha='right', va='center',
                fontsize=8, fontweight='bold', color='#ff9800', transform=ax.get_yaxis_transform())
        
        # Intrinsic value diamonds
        for label, iv, color in [('Conservative', cons_iv, '#4caf50'), ('Medium', med_iv, '#2196f3'), ('Optimistic', opt_iv, '#ff9800')]:
            ax.plot(0.75, iv, marker='D', markersize=10, color=color, zorder=5)
            ax.text(0.82, iv, f'${iv:.0f}', fontsize=8, va='center', color='#333333')
        
        # Current price line
        ax.axhline(y=price, color='red', linewidth=2.5, linestyle='--', zorder=4)
        ax.text(1.02, price, f'${price:.0f}\nTODAY', ha='left', va='center',
                fontsize=9, fontweight='bold', color='red', transform=ax.get_yaxis_transform())
        
        # Title
        ax.set_title(f"{data['name']}\n({ticker})", fontsize=13, fontweight='bold', pad=10)
        
        # Determine status
        if price <= cons_mos:
            status = "IN STRONG BUY ✓"
            status_color = '#2e7d32'
            box_color = '#c8e6c9'
        elif price <= med_mos:
            status = "IN BUY ZONE ✓"
            status_color = '#2e7d32'
            box_color = '#c8e6c9'
        elif price <= opt_mos:
            status = "FAIR VALUE"
            status_color = '#e65100'
            box_color = '#fff3e0'
        else:
            status = "OVERVALUED ✗"
            status_color = '#c62828'
            box_color = '#ffcdd2'
        
        # Status box at bottom
        bbox_props = dict(boxstyle="round,pad=0.5", facecolor=box_color, edgecolor=status_color, linewidth=2)
        ax.text(0.5, y_min + (y_max - y_min) * 0.03, status,
                ha='center', va='bottom', fontsize=10, fontweight='bold',
                color=status_color, bbox=bbox_props, transform=ax.transData,
                zorder=10)
        
        # Format y-axis
        ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x:,.0f}'))
        ax.tick_params(axis='y', labelsize=9)
        ax.grid(axis='y', alpha=0.3)
    
    # Legend at bottom
    legend_text = "Green = Conservative Buy (25% MoS)  |  Blue = Medium Buy (25% MoS)  |  Orange = Optimistic Buy (25% MoS)  |  Diamonds = Intrinsic Value  |  Red Dashed = Current Price"
    fig.text(0.5, 0.02, legend_text, ha='center', fontsize=8, color='#666666')
    
    plt.tight_layout(rect=[0.08, 0.05, 0.95, 0.92])
    path = os.path.join(OUT_DIR, "dcf-ai-adjusted-buy-zones.png")
    fig.savefig(path, dpi=200, bbox_inches='tight', facecolor='white')
    plt.close()
    print(f"\nSaved: {path}")


# ============================================================
# CHART 2: AI REVENUE IMPACT COMPARISON
# ============================================================

def create_revenue_impact_chart():
    fig, axes = plt.subplots(1, 3, figsize=(18, 10), dpi=200)
    fig.patch.set_facecolor('white')
    
    fig.suptitle("AI Revenue Impact — Current vs Projected 2030 Revenue Mix",
                 fontsize=16, fontweight='bold', y=0.97)
    fig.text(0.5, 0.935, "How Chatbot Advertising & AI Reshape Each Company's Revenue  |  Medium Scenario Projections",
             ha='center', fontsize=10, color='#555555')
    
    tickers = ['MSFT', 'AMZN', 'GOOGL']
    
    # Color palettes
    palettes = {
        'MSFT': ['#0078d4', '#00a4ef', '#7fba00', '#737373', '#f25022', '#ffb900', '#b4a7d6'],
        'AMZN': ['#ff9900', '#146eb4', '#232f3e', '#48a999', '#f5a623', '#888888'],
        'GOOGL': ['#4285f4', '#ea4335', '#34a853', '#fbbc04', '#673ab7', '#00bcd4', '#ff7043'],
    }
    
    for idx, ticker in enumerate(tickers):
        ax = axes[idx]
        data = companies[ticker]
        
        current = data['rev_current']
        projected = data['rev_2030']
        
        # Prepare data
        current_labels = list(current.keys())
        current_vals = list(current.values())
        proj_labels = list(projected.keys())
        proj_vals = list(projected.values())
        
        current_total = sum(current_vals)
        proj_total = sum(proj_vals)
        
        x = np.arange(2)
        bar_width = 0.6
        
        # Stacked bar chart
        palette = palettes[ticker]
        
        # Current bars
        bottom_c = 0
        bottom_p = 0
        legend_patches = []
        
        max_segments = max(len(current_labels), len(proj_labels))
        
        # We'll draw two stacked bars side by side
        ax_twin = ax
        
        # Current stack
        for i, (label, val) in enumerate(zip(current_labels, current_vals)):
            color = palette[i % len(palette)]
            ax.bar(0, val, bar_width, bottom=bottom_c, color=color, edgecolor='white', linewidth=0.5)
            if val / current_total > 0.08:
                ax.text(0, bottom_c + val/2, f'${val}B\n({val/current_total*100:.0f}%)',
                        ha='center', va='center', fontsize=7, fontweight='bold', color='white')
            bottom_c += val
        
        # Projected stack
        for i, (label, val) in enumerate(zip(proj_labels, proj_vals)):
            color = palette[i % len(palette)]
            ax.bar(1, val, bar_width, bottom=bottom_p, color=color, edgecolor='white', linewidth=0.5,
                   alpha=0.85, hatch='/' if 'AI' in label or 'Copilot' in label or 'Gemini' in label else '')
            if val / proj_total > 0.06:
                ax.text(1, bottom_p + val/2, f'${val}B\n({val/proj_total*100:.0f}%)',
                        ha='center', va='center', fontsize=7, fontweight='bold', color='white')
            bottom_p += val
        
        # Total labels on top
        ax.text(0, current_total + 8, f'${current_total}B', ha='center', fontsize=10, fontweight='bold')
        ax.text(1, proj_total + 8, f'${proj_total}B', ha='center', fontsize=10, fontweight='bold',
                color='#2e7d32')
        
        # Growth arrow/label
        growth_pct = (proj_total - current_total) / current_total * 100
        ax.text(0.5, max(current_total, proj_total) + 25, f'+{growth_pct:.0f}%',
                ha='center', fontsize=12, fontweight='bold', color='#2e7d32')
        
        ax.set_xticks([0, 1])
        ax.set_xticklabels(['2025\n(Current)', '2030\n(Projected)'], fontsize=10, fontweight='bold')
        ax.set_ylabel('Revenue ($B)', fontsize=10)
        ax.set_title(f"{data['name']} ({ticker})", fontsize=13, fontweight='bold', pad=10)
        
        # Y axis
        ax.set_ylim(0, max(current_total, proj_total) * 1.15)
        ax.yaxis.set_major_formatter(plt.FuncFormatter(lambda x, p: f'${x:,.0f}B'))
        ax.grid(axis='y', alpha=0.3)
        
        # Legend below each panel
        all_labels = proj_labels  # Use projected labels (more complete)
        handles = [mpatches.Patch(facecolor=palette[i % len(palette)], edgecolor='grey',
                                  label=all_labels[i]) for i in range(len(all_labels))]
        ax.legend(handles=handles, loc='upper left', fontsize=7, framealpha=0.9)
    
    # Highlight note
    fig.text(0.5, 0.02, "Hatched segments (/) indicate AI-driven revenue streams  |  Sources: Company filings, analyst estimates, OpenAI projections",
             ha='center', fontsize=8, color='#666666')
    
    plt.tight_layout(rect=[0.02, 0.05, 0.98, 0.92])
    path = os.path.join(OUT_DIR, "ai-revenue-impact-comparison.png")
    fig.savefig(path, dpi=200, bbox_inches='tight', facecolor='white')
    plt.close()
    print(f"Saved: {path}")


# ============================================================
# WORD DOCUMENT
# ============================================================

def create_docx():
    doc = Document()
    
    # Set default font
    style = doc.styles['Normal']
    font = style.font
    font.name = 'Calibri'
    font.size = Pt(11)
    
    # Title
    title = doc.add_heading('AI-Adjusted DCF Valuation Analysis', level=0)
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    
    subtitle = doc.add_paragraph()
    subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = subtitle.add_run('MSFT | AMZN | GOOGL — Factoring in Chatbot Advertising Revenue Streams')
    run.font.size = Pt(14)
    run.font.color.rgb = RGBColor(0x55, 0x55, 0x55)
    
    date_p = doc.add_paragraph()
    date_p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = date_p.add_run('Updated: March 31, 2026  |  10% Discount Rate  |  3% Terminal Growth  |  10-Year Projection')
    run.font.size = Pt(10)
    run.font.color.rgb = RGBColor(0x88, 0x88, 0x88)
    
    # ---- EXECUTIVE SUMMARY ----
    doc.add_heading('Executive Summary', level=1)
    doc.add_paragraph(
        'This analysis updates our DCF models for Microsoft, Amazon, and Alphabet to incorporate '
        'the emerging AI chatbot advertising revenue stream. On February 9, 2026, OpenAI launched '
        'advertising in ChatGPT at $60 CPM with a $200K minimum spend, targeting its 800M+ weekly '
        'active users. Google is actively monetizing AI Overviews with ads and planning Gemini ad '
        'placements for 2026. Amazon is exploring third-party chatbot ad sales and launched billable '
        'AI shopping prompts on March 25, 2026.'
    )
    doc.add_paragraph(
        'The key question: Does AI chatbot advertising represent a net-new TAM expansion for these '
        'companies, or does it cannibalize existing search advertising revenue? Our analysis suggests '
        'it is BOTH — with Microsoft and Amazon as net beneficiaries, and Google facing an asymmetric '
        'risk/reward profile where it must successfully cannibalize its own search ads to stay relevant.'
    )
    
    # ---- RESEARCH FINDINGS ----
    doc.add_heading('Chatbot Advertising Research Findings', level=1)
    
    doc.add_heading('OpenAI / ChatGPT Advertising', level=2)
    findings = [
        'Launched February 9, 2026 — ads appearing for Free and Go tier users',
        'Pricing: $60 CPM (cost per thousand impressions), $200K minimum spend',
        'Ad formats: Sponsored content within responses, sidebar placements, conversational ads',
        'Ads Manager in testing with weekly CSV reporting (no real-time dashboard yet)',
        'ChatGPT has 800M+ weekly active users as of late 2025',
        'OpenAI projects $46 billion in revenue from non-paying users by 2030 (ads + commissions)',
        'OpenAI\'s total 2026 revenue target: ~$25 billion (including subscriptions + API)',
        'Revenue share: Microsoft receives 20% of OpenAI\'s ChatGPT and API revenue',
        'Microsoft holds ~27% equity stake in OpenAI (post-PBC restructuring), plus profit-sharing rights',
        'OpenAI spent $5.02B on Azure inference in H1 CY2025 alone — massive Azure revenue driver',
    ]
    for f in findings:
        doc.add_paragraph(f, style='List Bullet')
    
    doc.add_heading('Google AI Advertising Strategy', level=2)
    findings_g = [
        'AI Overviews already show ads — expanding into AI Mode (most powerful AI search)',
        'Gemini chatbot ads targeted for 2026 rollout per advertiser briefings (Adweek Dec 2025)',
        'Google officially says "not ruling out" ads in Gemini — testing formats internally',
        'Gemini has 750M+ users, representing a massive monetization opportunity',
        'Google Cloud AI at $70B+ run rate, growing 30%+ YoY',
        'DOJ antitrust ruling could force changes to default search deals (Apple, Samsung)',
        'Gartner: 25% of online searches via AI chatbots by 2026, up from <5% in 2024',
        'Risk: Search ad revenue (55% of total) faces 20-30% erosion risk over 5-10 years from AI disruption',
    ]
    for f in findings_g:
        doc.add_paragraph(f, style='List Bullet')
    
    doc.add_heading('Amazon AI Commerce & Advertising', level=2)
    findings_a = [
        'AI Shopping Prompts became billable March 25, 2026 — contextual product recs at decision moments',
        'Exploring enabling third-party platforms to sell chatbot ads (ROIC.ai, March 2026)',
        'Creative Agent launched US Nov 2025, UK early 2026 — AI-generated ad campaigns',
        'Retail media network growing 25%+ YoY, AI supercharges targeting with first-party purchase data',
        'ChatGPT shopping integration with Shopify, Instacart, Target drives affiliate commerce TO Amazon',
        'AWS AI compute demand growing 30%+ as every company needs inference infrastructure',
        'Amazon is the INDIRECT beneficiary — chatbot shopping recommendations increase Amazon orders',
    ]
    for f in findings_a:
        doc.add_paragraph(f, style='List Bullet')
    
    # ---- DCF ANALYSIS ----
    doc.add_heading('DCF Valuation — Three Scenarios per Company', level=1)
    
    for ticker in ['MSFT', 'AMZN', 'GOOGL']:
        data = companies[ticker]
        r = results[ticker]
        
        doc.add_heading(f'{data["name"]} ({ticker})', level=2)
        
        # Key assumptions
        doc.add_heading('Key Assumptions', level=3)
        
        if ticker == 'MSFT':
            assumptions = [
                f'Base FCF: ${data["fcf"]}B (FY2025)  |  Revenue: ${data["revenue"]}B  |  Shares: {data["shares"]}B',
                'Azure AI growing 34% — largest cloud AI platform, inference revenue from OpenAI alone is massive',
                'OpenAI revenue share: MSFT receives 20% of ChatGPT + API revenue (~$5B in 2026, growing to $9B+ by 2030)',
                'OpenAI Azure compute: $10B+ annually flowing to Azure as inference costs (DIRECT revenue)',
                'Copilot subscriptions ($30/mo/user): Enterprise adoption accelerating, 10M+ seats by 2027',
                'GitHub Copilot: 2M+ paid subscribers, AI coding becoming standard developer tool',
                'ChatGPT ad revenue flowing to MSFT: 20% of estimated $3-5B in 2026 ad revenue = $0.6-1.0B',
            ]
        elif ticker == 'AMZN':
            assumptions = [
                f'Base FCF: ${data["fcf"]}B (FY2025)  |  Revenue: ${data["revenue"]}B  |  Shares: {data["shares"]}B',
                'AWS AI compute demand: Every major AI company (including OpenAI competitors) runs on AWS',
                'Retail media network: $60B+ in 2025, growing 25%+ as AI improves ad targeting',
                'AI Shopping Prompts (billable March 2026): New high-intent ad format with strong conversion data',
                'Chatbot commerce BENEFITS Amazon: When ChatGPT/Gemini recommend products, users buy on Amazon',
                'Amazon affiliate links in chatbots: Amazon Associates program is largest affiliate network globally',
                'Third-party chatbot ad platform: Amazon building infrastructure to monetize AI ads ACROSS platforms',
            ]
        else:  # GOOGL
            assumptions = [
                f'Base FCF: ${data["fcf"]}B (FY2025)  |  Revenue: ${data["revenue"]}B  |  Shares: {data["shares"]}B',
                'AI Overviews ads: Already live, testing in AI Mode — new ad format with strong commercial intent',
                'Gemini 750M users: Massive monetization opportunity if ads launch 2026',
                'Google Cloud AI: $70B+ run rate, major growth driver offsetting search erosion',
                'YouTube: Resilient at $50B+, AI-enhanced targeting and Shorts monetization improving',
                'RISK — Search ad erosion: 55% of revenue ($210B) exposed to AI chatbot competition',
                'RISK — DOJ antitrust: Could lose Apple/Samsung default search deals worth $20B+/yr in TAC payments',
                'Conservative scenario models aggressive 20-30% search revenue erosion over 5-10 years',
            ]
        for a in assumptions:
            doc.add_paragraph(a, style='List Bullet')
        
        # Results table
        doc.add_heading('Valuation Results', level=3)
        table = doc.add_table(rows=4, cols=5)
        table.style = 'Medium Shading 1 Accent 1'
        table.alignment = WD_TABLE_ALIGNMENT.CENTER
        
        headers = ['Scenario', 'FCF Growth (Yr 1-5)', 'FCF Growth (Yr 6-10)', 'Intrinsic Value', '25% MoS Buy Price']
        for i, h in enumerate(headers):
            table.rows[0].cells[i].text = h
        
        for row_idx, scenario in enumerate(['Conservative', 'Medium', 'Optimistic']):
            g1, g2 = data['scenarios'][scenario]
            rv = r[scenario]
            table.rows[row_idx + 1].cells[0].text = scenario
            table.rows[row_idx + 1].cells[1].text = f'{g1*100:.0f}%'
            table.rows[row_idx + 1].cells[2].text = f'{g2*100:.0f}%'
            table.rows[row_idx + 1].cells[3].text = f'${rv["iv"]:,.2f}'
            table.rows[row_idx + 1].cells[4].text = f'${rv["mos"]:,.2f}'
        
        doc.add_paragraph()
        
        # Current price vs valuations
        price = data['price']
        med_iv = r['Medium']['iv']
        upside = (med_iv - price) / price * 100
        
        p = doc.add_paragraph()
        run = p.add_run(f'Current Price: ${price:.2f}  |  Medium IV: ${med_iv:.2f}  |  ')
        run.font.bold = True
        if upside > 0:
            run2 = p.add_run(f'Upside: +{upside:.0f}%')
            run2.font.bold = True
            run2.font.color.rgb = RGBColor(0x2e, 0x7d, 0x32)
        else:
            run2 = p.add_run(f'Downside: {upside:.0f}%')
            run2.font.bold = True
            run2.font.color.rgb = RGBColor(0xc6, 0x28, 0x28)
    
    # ---- COMPARISON TABLE ----
    doc.add_heading('Side-by-Side Comparison', level=1)
    
    table = doc.add_table(rows=8, cols=4)
    table.style = 'Medium Shading 1 Accent 1'
    table.alignment = WD_TABLE_ALIGNMENT.CENTER
    
    headers = ['Metric', 'MSFT', 'AMZN', 'GOOGL']
    for i, h in enumerate(headers):
        table.rows[0].cells[i].text = h
    
    for row_idx, (label, key) in enumerate([
        ('Current Price', 'price'),
        ('Conservative IV', None),
        ('Medium IV', None),
        ('Optimistic IV', None),
        ('Conservative Buy (25% MoS)', None),
        ('Medium Buy (25% MoS)', None),
        ('Optimistic Buy (25% MoS)', None),
    ]):
        table.rows[row_idx + 1].cells[0].text = label
        for col_idx, ticker in enumerate(['MSFT', 'AMZN', 'GOOGL']):
            if key == 'price':
                table.rows[row_idx + 1].cells[col_idx + 1].text = f'${companies[ticker]["price"]:.2f}'
            elif 'IV' in label:
                scenario = label.split()[0]
                table.rows[row_idx + 1].cells[col_idx + 1].text = f'${results[ticker][scenario]["iv"]:,.2f}'
            elif 'Buy' in label:
                scenario = label.split()[0]
                table.rows[row_idx + 1].cells[col_idx + 1].text = f'${results[ticker][scenario]["mos"]:,.2f}'
    
    # ---- MUNGER INVERSION ----
    doc.add_heading('Munger Inversion: What Could Go Wrong?', level=1)
    doc.add_paragraph(
        '"Invert, always invert." — Charlie Munger. Before investing, we must consider what could destroy '
        'the thesis. Here are the key risks for each company:'
    )
    
    doc.add_heading('Microsoft — What Could Go Wrong', level=2)
    msft_risks = [
        'OpenAI relationship deteriorates: The partnership is complex and has shown cracks. If OpenAI builds its own infrastructure or partners with another cloud, MSFT loses ~$10B+ in Azure revenue AND the 20% revenue share.',
        'AI competition intensifies: Anthropic (on AWS/GCP), Google Gemini, Meta Llama — open-source models could commoditize AI, reducing Azure AI pricing power.',
        'Copilot adoption disappoints: At $30/user/month, enterprises may resist paying when free alternatives improve. If Copilot doesn\'t deliver measurable productivity gains, churn accelerates.',
        'ChatGPT ads underperform: $60 CPM is premium pricing. If advertisers don\'t see ROI vs Google/Meta, ad revenue stalls and MSFT\'s revenue share is immaterial.',
        'Antitrust exposure: MSFT\'s deep integration with OpenAI could face regulatory scrutiny globally.',
        'Capital allocation: $13B+ invested in OpenAI. If OpenAI never reaches profitability, this is a massive write-down risk.',
    ]
    for r_text in msft_risks:
        doc.add_paragraph(r_text, style='List Bullet')
    
    doc.add_heading('Amazon — What Could Go Wrong', level=2)
    amzn_risks = [
        'AWS growth decelerates: If AI workloads consolidate on Azure (OpenAI) or GCP (Gemini), AWS loses its cloud market share lead.',
        'Retail margin compression: AI-driven commerce comparison tools make price the ONLY factor, squeezing margins on retail operations.',
        'Chatbot disintermediation: Instead of driving traffic TO Amazon, chatbots could enable direct-to-consumer purchasing, bypassing Amazon entirely.',
        'CapEx spiral: $75B+ annual capital expenditure on data centers. If AI demand doesn\'t materialize at projected levels, massive overcapacity.',
        'Antitrust/regulation: FTC scrutiny of marketplace practices, potential forced separation of AWS from retail.',
        'AI advertising competition: Google and Meta have decades of ad tech expertise. Amazon\'s ad platform is newer and less sophisticated.',
    ]
    for r_text in amzn_risks:
        doc.add_paragraph(r_text, style='List Bullet')
    
    doc.add_heading('Alphabet/Google — What Could Go Wrong', level=2)
    googl_risks = [
        'Search ad revenue erosion accelerates: If 25% of searches move to chatbots by 2026 (Gartner), and 50% by 2030, Google loses $50-100B in annual revenue. This is the EXISTENTIAL risk.',
        'DOJ antitrust ruling: Loss of default search deals with Apple ($20B+/yr) would immediately crater traffic and revenue.',
        'AI Overviews cannibalize clicks: By answering queries directly, Google reduces the NEED for ads. Users don\'t click through to websites = fewer ad impressions.',
        'Gemini monetization fails: If users reject ads in Gemini (as they might in a conversational interface), the 750M user base generates zero ad revenue.',
        'Cloud competition: AWS and Azure are ahead in enterprise relationships. Google Cloud could lose the AI infrastructure race despite strong models.',
        'The "Innovator\'s Dilemma" in full force: Google MUST cannibalize its own search ad revenue to compete in AI. If it moves too slowly, ChatGPT/Perplexity win. If it moves too fast, revenue craters before new monetization scales.',
        'YouTube disruption: AI-generated content could flood the platform, reducing quality and advertiser trust.',
    ]
    for r_text in googl_risks:
        doc.add_paragraph(r_text, style='List Bullet')
    
    # ---- BOTTOM LINE ----
    doc.add_heading('Bottom Line Assessment', level=1)
    
    doc.add_heading('Microsoft (MSFT) — BUY ZONE', level=2)
    doc.add_paragraph(
        f'At ${companies["MSFT"]["price"]}, MSFT trades below the Medium scenario MoS buy price of '
        f'${results["MSFT"]["Medium"]["mos"]}. Microsoft is the clearest AI beneficiary: they collect '
        'Azure infrastructure revenue from OpenAI ($10B+/yr), a 20% revenue share on ChatGPT ($5B+ in 2026), '
        'and their own Copilot/GitHub AI subscriptions are growing rapidly. The AI chatbot advertising '
        'wave is a TAILWIND for Microsoft — they get paid whether OpenAI\'s ads succeed (revenue share) '
        'or whether enterprises build their own AI (Azure compute). This is the picks-and-shovels play. '
        'BUY at current levels with conviction.'
    )
    
    doc.add_heading('Amazon (AMZN) — BUY ZONE', level=2)
    doc.add_paragraph(
        f'At ${companies["AMZN"]["price"]}, AMZN is near the Conservative MoS buy price of '
        f'${results["AMZN"]["Conservative"]["mos"]}. Amazon is the INDIRECT winner of AI chatbot commerce. '
        'Every time ChatGPT or Gemini recommends a product, there\'s a high probability the user buys it '
        'on Amazon. The retail media network ($60B+) is being supercharged by AI targeting. AWS remains '
        'the infrastructure backbone for AI startups (excluding OpenAI). The new AI Shopping Prompts '
        '(billable March 2026) represent a high-margin revenue stream. At current prices, AMZN offers '
        'significant upside to the Medium scenario valuation.'
    )
    
    doc.add_heading('Alphabet (GOOGL) — MOST COMPLEX / PROCEED WITH CAUTION', level=2)
    doc.add_paragraph(
        f'At ${companies["GOOGL"]["price"]}, GOOGL trades above the Optimistic MoS buy price of '
        f'${results["GOOGL"]["Optimistic"]["mos"]}. This is the most nuanced call. Google has enormous '
        'assets — Search ($210B), YouTube ($50B), Cloud ($70B), Gemini (750M users) — but the AI chatbot '
        'advertising revolution threatens its CORE business model. The Conservative scenario (4%/3% growth) '
        'reflects genuine search ad erosion risk. The Optimistic scenario (14%/10%) assumes Google '
        'successfully monetizes AI while defending search. The DOJ antitrust ruling adds another layer '
        'of uncertainty. At $282, the stock prices in the medium-to-optimistic scenario with no room for '
        'error. Wait for a pullback to the Medium MoS buy price or below before building a position.'
    )
    
    # ---- METHODOLOGY ----
    doc.add_heading('Methodology & Disclaimers', level=1)
    doc.add_paragraph(
        'Two-stage Discounted Cash Flow model. Phase 1: Years 1-5 with higher growth rates reflecting '
        'AI monetization ramp. Phase 2: Years 6-10 with moderating growth as AI revenue matures. '
        'Terminal value calculated using Gordon Growth Model with 3% perpetual growth rate. '
        'All cash flows discounted at 10% WACC. Intrinsic values calculated per share. '
        'Margin of Safety buy prices set at 75% of intrinsic value (25% discount). '
        'This is NOT investment advice. Do your own due diligence.'
    )
    
    path = os.path.join(OUT_DIR, "dcf-ai-adjusted-analysis.docx")
    doc.save(path)
    print(f"Saved: {path}")


# ============================================================
# MAIN
# ============================================================

if __name__ == '__main__':
    print("=" * 60)
    print("AI-ADJUSTED DCF VALUATION ANALYSIS")
    print("March 31, 2026")
    print("=" * 60)
    
    create_buy_zones_chart()
    create_revenue_impact_chart()
    create_docx()
    
    print("\n" + "=" * 60)
    print("ALL FILES GENERATED SUCCESSFULLY")
    print("=" * 60)
