#!/usr/bin/env python3
"""
Step 5: Investment Thesis & Risk Assessment Synthesis
======================================================
Synthesizes findings from Steps 1-4 into a comprehensive investment thesis
and risk assessment for the Chegg (CHGG) short position analysis.

Author: K-Dense Coding Agent
Date: 2026-02-03
"""

import json
import pandas as pd
import numpy as np
from pathlib import Path
from datetime import datetime

# Set up paths
BASE_DIR = Path('/app/sandbox/session_20260203_085912_030e6e80a419')
DATA_DIR = BASE_DIR / 'data'
RESULTS_DIR = BASE_DIR / 'results'

print("=" * 80)
print("STEP 5: INVESTMENT THESIS & RISK ASSESSMENT SYNTHESIS")
print("=" * 80)
print(f"Analysis Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print()

# =============================================================================
# 1. LOAD DATA FROM PREVIOUS STEPS
# =============================================================================
print("Loading data from previous analyses...")

# Load financial metrics
financial_df = pd.read_csv(RESULTS_DIR / 'financial_metrics_history.csv')
financial_df['Date'] = pd.to_datetime(financial_df['Date'])

# Load income statement for R&D data
income_df = pd.read_csv(DATA_DIR / 'chgg_income_statement_annual.csv')
income_df['Date'] = pd.to_datetime(income_df['Date'])
income_df = income_df.sort_values('Date', ascending=False).reset_index(drop=True)

# Load key stats
with open(DATA_DIR / 'chgg_key_stats.json', 'r') as f:
    key_stats = json.load(f)

# Load technical indicators
tech_df = pd.read_csv(RESULTS_DIR / 'technical_indicators.csv')

# Load valuation scenarios
val_df = pd.read_csv(RESULTS_DIR / 'valuation_scenarios.csv')

print(f"  - Financial metrics: {len(financial_df)} years of data")
print(f"  - Income statements: {len(income_df)} years of data")
print(f"  - Technical indicators loaded")
print(f"  - Valuation scenarios loaded")
print()

# =============================================================================
# 2. EXTRACT KEY METRICS
# =============================================================================
print("Extracting key metrics...")

# Current market data
current_price = key_stats.get('fiftyTwoWeekLow', 0.44) + 0.29  # ~$0.73 as per sentiment
market_cap = key_stats.get('marketCap', 76742504) / 1e6  # $76.7M
enterprise_value = key_stats.get('enterpriseValue', 66787896) / 1e6  # $66.8M
shares_outstanding = key_stats.get('sharesOutstanding', 109273108) / 1e6  # 109.3M
book_value_per_share = key_stats.get('bookValue', 1.343)
total_cash = key_stats.get('totalCash', 96389000) / 1e6  # $96.4M
total_debt = key_stats.get('totalDebt', 83036000) / 1e6  # $83M
ttm_revenue = key_stats.get('totalRevenue', 447732992) / 1e6  # $447.7M
ttm_fcf = key_stats.get('freeCashflow', 45076248) / 1e6  # $45.1M
revenue_growth = key_stats.get('revenueGrowth', -0.431)  # -43.1%

# Get 52-week range
fifty_two_week_high = key_stats.get('fiftyTwoWeekHigh', 1.90)
fifty_two_week_low = key_stats.get('fiftyTwoWeekLow', 0.44)

# Short interest metrics
short_ratio = key_stats.get('shortRatio', 5.66)
short_pct_float = key_stats.get('shortPercentOfFloat', 0.0594) * 100  # 5.94%

# Technical levels
sma_50 = tech_df['SMA_50'].iloc[0]
sma_200 = tech_df['SMA_200'].iloc[0]
rsi = tech_df['RSI_14'].iloc[0]

print(f"  - Current Price: ${current_price:.2f}")
print(f"  - Market Cap: ${market_cap:.1f}M")
print(f"  - Enterprise Value: ${enterprise_value:.1f}M")
print(f"  - 52-Week Range: ${fifty_two_week_low:.2f} - ${fifty_two_week_high:.2f}")
print()

# =============================================================================
# 3. REVENUE DECLINE ANALYSIS
# =============================================================================
print("=" * 60)
print("REVENUE DECLINE TRAJECTORY")
print("=" * 60)

# Historical revenue data
revenue_history = []
for idx, row in financial_df.iterrows():
    year = pd.to_datetime(row['Date']).year
    revenue = row['Total_Revenue'] / 1e6
    yoy_growth = row.get('Revenue_YoY_Growth', np.nan)
    revenue_history.append({'Year': year, 'Revenue': revenue, 'YoY_Growth': yoy_growth})

revenue_history_df = pd.DataFrame(revenue_history)
print("Annual Revenue (in $M):")
for _, row in revenue_history_df.iterrows():
    growth_str = f"({row['YoY_Growth']:+.1f}%)" if pd.notna(row['YoY_Growth']) else ""
    print(f"  {int(row['Year'])}: ${row['Revenue']:.1f}M {growth_str}")

print(f"\nTTM Revenue: ${ttm_revenue:.1f}M ({revenue_growth*100:.1f}% YoY)")

# Calculate revenue decline from peak
peak_revenue = revenue_history_df['Revenue'].max()
peak_year = int(revenue_history_df.loc[revenue_history_df['Revenue'].idxmax(), 'Year'])
decline_from_peak = (ttm_revenue - peak_revenue) / peak_revenue * 100

print(f"\nPeak Revenue (${peak_year}): ${peak_revenue:.1f}M")
print(f"Decline from Peak: {decline_from_peak:.1f}%")
print()

# =============================================================================
# 4. CASH BURN ANALYSIS
# =============================================================================
print("=" * 60)
print("CASH BURN & RUNWAY ANALYSIS")
print("=" * 60)

# FCF history
fcf_history = []
for idx, row in financial_df.iterrows():
    year = pd.to_datetime(row['Date']).year
    fcf = row['Free_Cash_Flow'] / 1e6
    fcf_history.append({'Year': year, 'FCF': fcf})

fcf_df = pd.DataFrame(fcf_history)
print("Annual Free Cash Flow (in $M):")
for _, row in fcf_df.iterrows():
    status = "POSITIVE" if row['FCF'] > 0 else "NEGATIVE"
    print(f"  {int(row['Year'])}: ${row['FCF']:.1f}M [{status}]")

# Latest quarter burn rate calculation
avg_quarterly_fcf = ttm_fcf / 4
print(f"\nTTM Free Cash Flow: ${ttm_fcf:.1f}M")
print(f"Average Quarterly FCF: ${avg_quarterly_fcf:.1f}M")

# Cash runway
if avg_quarterly_fcf < 0:
    runway_quarters = total_cash / abs(avg_quarterly_fcf)
    runway_years = runway_quarters / 4
    print(f"Cash Runway: ~{runway_years:.1f} years")
else:
    print("Cash Runway: POSITIVE FCF - No immediate burn")

print(f"\nCurrent Cash: ${total_cash:.1f}M")
print(f"Current Debt: ${total_debt:.1f}M")
print(f"Net Cash Position: ${total_cash - total_debt:.1f}M")
print()

# =============================================================================
# 5. R&D SPENDING ANALYSIS (AI PIVOT CREDIBILITY)
# =============================================================================
print("=" * 60)
print("R&D INVESTMENT ANALYSIS (AI PIVOT CREDIBILITY)")
print("=" * 60)

# Extract R&D spending
rd_data = []
for _, row in income_df.iterrows():
    year = pd.to_datetime(row['Date']).year
    rd = row.get('Research And Development', 0) / 1e6
    revenue = row.get('Total Revenue', 0) / 1e6
    rd_pct = (rd / revenue * 100) if revenue > 0 else 0
    rd_data.append({'Year': year, 'R&D': rd, 'Revenue': revenue, 'R&D_Pct': rd_pct})

rd_df = pd.DataFrame(rd_data).sort_values('Year')
print("R&D Spending vs Revenue:")
for _, row in rd_df.iterrows():
    print(f"  {int(row['Year'])}: R&D=${row['R&D']:.1f}M, Revenue=${row['Revenue']:.1f}M ({row['R&D_Pct']:.1f}% of revenue)")

# Calculate R&D trends
latest_rd = rd_df[rd_df['Year'] == rd_df['Year'].max()]['R&D'].values[0]
peak_rd = rd_df['R&D'].max()
rd_decline = (latest_rd - peak_rd) / peak_rd * 100

print(f"\nPeak R&D: ${peak_rd:.1f}M")
print(f"Latest R&D: ${latest_rd:.1f}M")
print(f"R&D Decline: {rd_decline:.1f}%")

# AI pivot credibility assessment
avg_rd_pct = rd_df['R&D_Pct'].mean()
print(f"\nAverage R&D as % of Revenue: {avg_rd_pct:.1f}%")
print()

# Compare to AI competitors (rough benchmarks)
ai_competitor_rd_ratios = {
    'OpenAI (est.)': 80,
    'Anthropic (est.)': 70,
    'Google DeepMind (est.)': 30,
    'Chegg': avg_rd_pct
}

print("R&D Intensity Comparison:")
for company, ratio in ai_competitor_rd_ratios.items():
    print(f"  {company}: {ratio:.0f}% of revenue")

print("\nAI PIVOT CREDIBILITY ASSESSMENT: LOW")
print(f"  - R&D declining while revenue falls (not accelerating investment)")
print(f"  - R&D intensity ({avg_rd_pct:.1f}%) far below AI leaders (30-80%)")
print(f"  - Cannot compete with $10B+ AI infrastructure investments")
print()

# =============================================================================
# 6. PRIVATIZATION RISK ANALYSIS (BULL CASE REBUTTAL)
# =============================================================================
print("=" * 60)
print("PRIVATIZATION RISK ANALYSIS (BULL CASE QUANTIFICATION)")
print("=" * 60)

# Get EBITDA from income statement (Normalized EBITDA)
latest_ebitda = income_df[income_df['Date'].dt.year == 2024]['Normalized EBITDA'].values
if len(latest_ebitda) > 0:
    ebitda = latest_ebitda[0] / 1e6
else:
    # Calculate from EV/EBITDA if available
    ebitda = enterprise_value / key_stats.get('enterpriseToEbitda', 2.0)

print(f"Latest Normalized EBITDA: ${ebitda:.1f}M")
print(f"Current Enterprise Value: ${enterprise_value:.1f}M")
print(f"Current EV/EBITDA: {enterprise_value/ebitda:.1f}x")
print()

# Calculate implied buyout prices at various EBITDA multiples
print("Implied Buyout Prices at Various EBITDA Multiples:")
print("-" * 60)

ebitda_multiples = [2, 3, 4, 5, 6, 8, 10]
buyout_analysis = []

for multiple in ebitda_multiples:
    implied_ev = ebitda * multiple
    implied_equity_value = implied_ev - total_debt + total_cash
    implied_price = implied_equity_value / shares_outstanding
    premium_to_current = (implied_price - current_price) / current_price * 100

    buyout_analysis.append({
        'Multiple': multiple,
        'Implied_EV': implied_ev,
        'Implied_Equity': implied_equity_value,
        'Implied_Price': implied_price,
        'Premium': premium_to_current
    })

    premium_str = f"+{premium_to_current:.0f}%" if premium_to_current > 0 else f"{premium_to_current:.0f}%"
    print(f"  {multiple}x EBITDA: EV=${implied_ev:.0f}M → ${implied_price:.2f}/share ({premium_str} vs current)")

buyout_df = pd.DataFrame(buyout_analysis)

# Typical PE buyout metrics
print("\n" + "-" * 60)
print("PRIVATIZATION FEASIBILITY ASSESSMENT:")
print("-" * 60)
print(f"  - At 3x EBITDA: ${buyout_df[buyout_df['Multiple']==3]['Implied_Price'].values[0]:.2f}/share")
print(f"    (Distressed buyout - minimal premium, unlikely to attract interest)")
print(f"  - At 5x EBITDA: ${buyout_df[buyout_df['Multiple']==5]['Implied_Price'].values[0]:.2f}/share")
print(f"    (Fair value buyout - still requires belief in turnaround)")
print(f"  - At 8x EBITDA: ${buyout_df[buyout_df['Multiple']==8]['Implied_Price'].values[0]:.2f}/share")
print(f"    (Premium buyout - highly unlikely given structural decline)")

print("\nKEY INSIGHT: Even at 8x EBITDA (generous for declining business),")
print(f"buyout price would only be ${buyout_df[buyout_df['Multiple']==8]['Implied_Price'].values[0]:.2f}/share.")
print("No rational acquirer would pay a premium for a structurally disrupted business.")
print()

# =============================================================================
# 7. TRADE STRUCTURE DEFINITION
# =============================================================================
print("=" * 60)
print("TRADE STRUCTURE DEFINITION")
print("=" * 60)

# Define key levels based on technical analysis
key_support = fifty_two_week_low  # $0.44
key_resistance = sma_50  # ~$0.89
current = current_price

# Calculate targets based on valuation analysis
# Bear case: $0.12
# Liquidation: $0.50
# Base case: $0.92
# Bull case: $2.91

# Short entry parameters
entry_range_low = 0.70  # Current levels
entry_range_high = 0.90  # Near 50-day SMA resistance

# Stop loss: Above recent resistance with buffer
stop_loss = round(sma_50 * 1.15, 2)  # 15% above 50-day SMA

# Price targets
target_base = 0.50  # Liquidation value
target_bear = 0.25  # Between liquidation and bear DCF
target_extreme = 0.12  # Bear case DCF

print(f"Current Price: ${current:.2f}")
print(f"50-Day SMA: ${sma_50:.2f}")
print(f"200-Day SMA: ${sma_200:.2f}")
print(f"RSI: {rsi:.1f} (OVERSOLD)")
print()

print("RECOMMENDED TRADE STRUCTURE:")
print("-" * 40)
print(f"  Entry Zone:      ${entry_range_low:.2f} - ${entry_range_high:.2f}")
print(f"  Stop Loss:       ${stop_loss:.2f} (+{((stop_loss-current)/current*100):.0f}% from current)")
print(f"  Target 1 (Base): ${target_base:.2f} (-{((current-target_base)/current*100):.0f}%)")
print(f"  Target 2 (Bear): ${target_bear:.2f} (-{((current-target_bear)/current*100):.0f}%)")
print(f"  Target 3 (Extr): ${target_extreme:.2f} (-{((current-target_extreme)/current*100):.0f}%)")
print()

# Risk/reward calculation
risk = stop_loss - current
reward_base = current - target_base
reward_bear = current - target_bear

print("RISK/REWARD ANALYSIS:")
print(f"  Risk (to stop): ${risk:.2f} ({risk/current*100:.1f}%)")
print(f"  Reward (Target 1): ${reward_base:.2f} ({reward_base/current*100:.1f}%)")
print(f"  Risk/Reward Ratio: 1:{reward_base/risk:.1f}")
print()

# Position sizing guidance
print("POSITION SIZING GUIDANCE:")
print("-" * 40)
print("  Given:")
print(f"    - Market cap: ${market_cap:.1f}M (micro-cap, HIGH VOLATILITY)")
print(f"    - Short interest: {short_pct_float:.1f}% (moderate, NOT crowded)")
print(f"    - Days to cover: {short_ratio:.1f} days (orderly exit possible)")
print(f"    - Beta: {key_stats.get('beta', 1.98):.2f} (HIGH VOLATILITY)")
print()
print("  Recommendations:")
print("    - Maximum position: 2-3% of portfolio")
print("    - Use options if available to define risk")
print("    - Consider scaling in: 50% initial, 50% on confirmation")
print("    - Tight stop discipline critical due to volatility")
print()

# =============================================================================
# 8. KEY CATALYSTS
# =============================================================================
print("=" * 60)
print("KEY CATALYSTS (POTENTIAL TRIGGERS)")
print("=" * 60)

catalysts = [
    {
        'event': 'Q4 2025 / Q1 2026 Earnings',
        'timing': 'Every ~3 months',
        'impact': 'Continued subscriber losses confirm structural decline',
        'direction': 'NEGATIVE'
    },
    {
        'event': 'Guidance Reduction',
        'timing': 'Any earnings call',
        'impact': 'Management admits further deterioration',
        'direction': 'NEGATIVE'
    },
    {
        'event': 'Cash Burn Acceleration',
        'timing': 'Ongoing',
        'impact': 'If cost cuts fail, liquidity becomes concern',
        'direction': 'NEGATIVE'
    },
    {
        'event': 'AI Competition Intensifies',
        'timing': 'Continuous',
        'impact': 'ChatGPT, Gemini, Claude improvements erode value prop',
        'direction': 'NEGATIVE'
    },
    {
        'event': 'Debt Maturity / Refinancing',
        'timing': 'Check debt schedule',
        'impact': 'Refinancing at higher rates or covenant breach',
        'direction': 'NEGATIVE'
    },
    {
        'event': 'Workforce Reductions',
        'timing': 'Ongoing',
        'impact': 'Further cuts signal management capitulation',
        'direction': 'MIXED'
    },
    {
        'event': 'Strategic Review / M&A Rumor',
        'timing': 'Potential',
        'impact': 'Could spark short-term rally (exit trigger)',
        'direction': 'POSITIVE'
    },
    {
        'event': 'Short Squeeze (Technical)',
        'timing': 'Any time',
        'impact': 'With only 6% short interest, limited squeeze potential',
        'direction': 'POSITIVE (temporary)'
    }
]

for i, cat in enumerate(catalysts, 1):
    print(f"{i}. {cat['event']} [{cat['direction']}]")
    print(f"   Timing: {cat['timing']}")
    print(f"   Impact: {cat['impact']}")
    print()

# =============================================================================
# 9. GENERATE COMPREHENSIVE THESIS DOCUMENT
# =============================================================================
print("=" * 60)
print("GENERATING INVESTMENT THESIS DOCUMENT")
print("=" * 60)

thesis_document = f"""
================================================================================
CHEGG INC. (CHGG) - INVESTMENT THESIS SYNTHESIS
Short Position Analysis & Risk Assessment
================================================================================
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
Analysis Period: 2021-2024 (Annual) + TTM
Current Price: ${current_price:.2f}

================================================================================
SECTION 1: CORE THESIS - "THE VARIANT PERCEPTION"
================================================================================

THESIS STATEMENT:
The market is pricing Chegg as a distressed-but-recovering education technology
company. We believe this is STILL too optimistic. The structural disruption from
AI (ChatGPT, Claude, Gemini) has permanently impaired Chegg's business model,
and the market has not fully discounted the terminal decline scenario.

WHY THE MARKET IS WRONG:
1. Revenue decline is ACCELERATING, not stabilizing
   - 2022: -1.2%
   - 2023: -6.6%
   - 2024: -13.8%
   - TTM: {revenue_growth*100:.1f}%

2. The "AI pivot" narrative is not credible
   - R&D spending is DECLINING while revenue falls
   - R&D intensity ({avg_rd_pct:.1f}% of revenue) is far below AI leaders (30-80%)
   - Cannot compete with OpenAI/Google's $10B+ infrastructure investments

3. Valuation still implies survival
   - Trading at 0.52x book value implies distress but not failure
   - Reverse DCF shows market pricing -35% perpetual growth
   - Should be priced closer to liquidation value (${book_value_per_share * 0.4:.2f}-$0.50)

VARIANT PERCEPTION:
While the market sees a "cheap, beaten-down stock that could bounce," we see a
structurally disrupted business with no path to relevance in the AI era. The
question is not IF Chegg goes to zero, but HOW LONG the decline takes.

================================================================================
SECTION 2: FINANCIAL DETERIORATION EVIDENCE
================================================================================

REVENUE COLLAPSE:
- Peak Revenue (2021): ${peak_revenue:.0f}M
- TTM Revenue: ${ttm_revenue:.0f}M
- Decline from Peak: {decline_from_peak:.1f}%
- Acceleration: Decline rate has 10x'd in 3 years

MARGIN DESTRUCTION:
- Operating margin: +10% (2022) → -10% (2024)
- Net profit margin: -135% in 2024 (massive impairment)
- $677M goodwill write-down acknowledges permanent impairment

LIQUIDITY STRESS:
- Current ratio: {key_stats.get('currentRatio', 0.95):.2f}x (<1.0 = short-term pressure)
- Quick ratio: {key_stats.get('quickRatio', 0.78):.2f}x (limited buffer)
- Despite aggressive debt reduction, ratios still concerning

CASH POSITION:
- Cash: ${total_cash:.1f}M
- Debt: ${total_debt:.1f}M
- Net Cash: ${total_cash - total_debt:.1f}M
- TTM FCF: ${ttm_fcf:.1f}M (still positive, but declining)

================================================================================
SECTION 3: BULL CASE REBUTTAL - PRIVATIZATION ANALYSIS
================================================================================

BULL CASE: "A PE firm could take Chegg private at a premium."

REBUTTAL:

1. VALUATION MATH DOESN'T WORK:
   Current EBITDA: ${ebitda:.1f}M

   At various EBITDA multiples:
"""

for _, row in buyout_df.iterrows():
    premium_str = f"+{row['Premium']:.0f}%" if row['Premium'] > 0 else f"{row['Premium']:.0f}%"
    thesis_document += f"   - {int(row['Multiple'])}x EBITDA: ${row['Implied_Price']:.2f}/share ({premium_str})\n"

thesis_document += f"""
2. WHY NO RATIONAL BUYER EXISTS:
   - Declining revenue = shrinking cash flows = declining EBITDA
   - 3-5x EBITDA typical for distressed deals, yielding ${buyout_df[buyout_df['Multiple']==4]['Implied_Price'].values[0]:.2f}/share
   - No synergies with strategic acquirers (who would buy a disrupted ed-tech?)
   - PE firms require growth or turnaround path; Chegg has neither

3. PRIVATIZATION FLOOR:
   - Realistic floor: ${buyout_df[buyout_df['Multiple']==3]['Implied_Price'].values[0]:.2f}-${buyout_df[buyout_df['Multiple']==5]['Implied_Price'].values[0]:.2f}/share
   - This is NOT materially above current price
   - Risk/reward asymmetric: limited upside from privatization, significant
     downside to liquidation

CONCLUSION: Privatization is not a credible bull case. Even if it happened,
the premium would be minimal and would still represent a loss for anyone
buying above ${buyout_df[buyout_df['Multiple']==4]['Implied_Price'].values[0]:.2f}/share.

================================================================================
SECTION 4: BULL CASE REBUTTAL - AI PIVOT ANALYSIS
================================================================================

BULL CASE: "Chegg can pivot to AI-powered tutoring and compete."

REBUTTAL:

1. R&D INVESTMENT IS INADEQUATE:
   Year    R&D ($M)    % of Revenue    Direction
"""

for _, row in rd_df.iterrows():
    prev_year_data = rd_df[rd_df['Year'] == row['Year']-1]
    if row['Year'] > rd_df['Year'].min() and len(prev_year_data) > 0 and row['R&D'] < prev_year_data['R&D'].values[0]:
        direction = "DOWN"
    else:
        direction = "--"
    thesis_document += f"   {int(row['Year'])}     ${row['R&D']:.0f}M       {row['R&D_Pct']:.1f}%            {direction}\n"

thesis_document += f"""
2. COMPETITIVE DISADVANTAGE:
   Company          R&D Intensity    Investment Scale
   OpenAI           ~80%             $10B+ raised
   Anthropic        ~70%             $4B+ raised
   Google AI        ~30%             $100B+ infrastructure
   Chegg            ~{avg_rd_pct:.0f}%             ${latest_rd:.0f}M declining

3. WHY THE AI PIVOT FAILS:
   - Foundation models (GPT-4, Claude, Gemini) ARE the product
   - Chegg's "AI" is just a wrapper on these models
   - Students can access the same AI directly for free or cheaper
   - No proprietary data advantage; textbook solutions are commodity
   - Brand association with "cheating" is liability in AI era

4. THE MATH:
   - Chegg spent ${latest_rd:.0f}M on R&D in 2024
   - OpenAI raised $6.6B in a single round
   - Chegg's TOTAL market cap: ${market_cap:.0f}M (1% of one OpenAI raise)

CONCLUSION: Chegg cannot out-innovate companies with 100x the resources building
the core technology that has disrupted Chegg's business. The AI pivot narrative
is a distraction from the fundamental reality of structural decline.

================================================================================
SECTION 5: TRADE SETUP - ACTIONABLE GUIDANCE
================================================================================

CURRENT TECHNICAL PICTURE:
- Price: ${current_price:.2f}
- 50-day SMA: ${sma_50:.2f} (RESISTANCE)
- 200-day SMA: ${sma_200:.2f} (RESISTANCE)
- RSI: {rsi:.1f} (OVERSOLD - expect bounces)
- Trend: STRONG DOWNTREND

ENTRY PARAMETERS:
- Primary Entry Zone: ${entry_range_low:.2f} - ${entry_range_high:.2f}
- Optimal Entry: Near 50-day SMA (${sma_50:.2f}) on failed rally
- Alternative: Scale in at current levels with tight stops

STOP LOSS:
- Hard Stop: ${stop_loss:.2f} (+{((stop_loss-current_price)/current_price*100):.0f}% from current)
- Rationale: Above 50-day SMA + buffer for volatility
- Risk per share: ${stop_loss - current_price:.2f}

PRICE TARGETS:
1. Target 1 (Base Case): ${target_base:.2f}
   - Based on: Liquidation value
   - Probability: 50%
   - Return: -{((current_price-target_base)/current_price*100):.0f}%

2. Target 2 (Bear Case): ${target_bear:.2f}
   - Based on: Accelerated decline + margin pressure
   - Probability: 35%
   - Return: -{((current_price-target_bear)/current_price*100):.0f}%

3. Target 3 (Extreme Bear): ${target_extreme:.2f}
   - Based on: Near-bankruptcy pricing
   - Probability: 15%
   - Return: -{((current_price-target_extreme)/current_price*100):.0f}%

RISK/REWARD PROFILE:
- Risk: {((stop_loss-current_price)/current_price*100):.0f}% to stop
- Reward (probability-weighted): ~{((current_price-target_base)/current_price*100)*0.5 + ((current_price-target_bear)/current_price*100)*0.35 + ((current_price-target_extreme)/current_price*100)*0.15:.0f}%
- Ratio: ~1:{reward_base/risk:.1f}

POSITION SIZING:
- Maximum allocation: 2-3% of portfolio
- Reasoning:
  * Micro-cap (${market_cap:.0f}M) = HIGH volatility
  * Beta {key_stats.get('beta', 1.98):.1f} = moves 2x the market
  * Short interest {short_pct_float:.1f}% = manageable but watch for squeezes
  * Days to cover: {short_ratio:.1f} = orderly exit possible

EXECUTION STRATEGY:
1. Initial position: 50% of target size at current levels
2. Add 25% if price rallies to 50-day SMA (better entry)
3. Add final 25% on next earnings miss confirmation
4. Scale out: 50% at Target 1, 30% at Target 2, hold 20% for optionality

================================================================================
SECTION 6: KEY CATALYSTS TO MONITOR
================================================================================

NEGATIVE CATALYSTS (SHORT-FAVORABLE):
"""

for cat in [c for c in catalysts if 'NEGATIVE' in c['direction']]:
    thesis_document += f"• {cat['event']}: {cat['impact']}\n"

thesis_document += """
POSITIVE CATALYSTS (COVER TRIGGERS):
"""

for cat in [c for c in catalysts if 'POSITIVE' in c['direction']]:
    thesis_document += f"• {cat['event']}: {cat['impact']}\n"

thesis_document += f"""
CALENDAR EVENTS:
- Earnings: Typically February, May, August, November
- Key focus: Subscriber count, revenue guidance, cash burn

================================================================================
SECTION 7: RISK FACTORS
================================================================================

1. SHORT SQUEEZE RISK: MODERATE
   - Short interest: {short_pct_float:.1f}% (NOT crowded)
   - Days to cover: {short_ratio:.1f}
   - Assessment: Orderly covering possible, no GME-style dynamics

2. TAKEOVER RISK: LOW
   - No strategic rationale for acquirers
   - Privatization math doesn't work (see Section 3)
   - Distressed asset specialists want deeper discounts

3. TECHNICAL BOUNCE RISK: HIGH
   - RSI at {rsi:.1f} (oversold territory)
   - Expect 20-40% bounces on oversold conditions
   - Mitigation: Use stops, scale positions

4. POSITIVE SURPRISE RISK: LOW
   - Would require reversal of structural AI disruption
   - No evidence of subscriber stabilization
   - Cost cuts already priced in

5. LIQUIDITY RISK: MODERATE
   - ${market_cap:.0f}M market cap = wide spreads possible
   - Volume declining = harder to exit large positions
   - Mitigation: Size appropriately, use limit orders

================================================================================
SECTION 8: CONCLUSION & RECOMMENDATION
================================================================================

INVESTMENT THESIS: MAINTAIN SHORT POSITION

The Chegg short thesis remains intact. The company faces structural disruption
from AI that has permanently impaired its business model. While the stock has
declined 99%+ from its highs, we believe further downside exists as the market
fully prices in the terminal decline scenario.

KEY CONVICTION POINTS:
1. Revenue decline is accelerating, not stabilizing
2. AI pivot is not credible given inadequate R&D investment
3. Privatization is not a meaningful bull case at realistic multiples
4. Valuation still implies survival; should price for liquidation/failure
5. Technical setup remains bearish with oversold bounces offering entry points

EXPECTED OUTCOME:
- Base case: Stock declines to ${target_base:.2f} (liquidation value) = -{((current_price-target_base)/current_price*100):.0f}%
- Bear case: Stock declines to ${target_bear:.2f} = -{((current_price-target_bear)/current_price*100):.0f}%
- Time horizon: 6-18 months

RISK MANAGEMENT:
- Stop loss at ${stop_loss:.2f} limits downside to {((stop_loss-current_price)/current_price*100):.0f}%
- Position size at 2-3% keeps portfolio risk manageable
- Scaling strategy allows optimization of entry

================================================================================
DISCLAIMER
================================================================================
This analysis is for informational purposes only and does not constitute
investment advice. Short selling involves unlimited risk. Past performance
does not guarantee future results. Always conduct your own due diligence.

================================================================================
END OF INVESTMENT THESIS DOCUMENT
================================================================================
"""

# Write the thesis document
output_path = RESULTS_DIR / 'investment_thesis_synthesis.txt'
with open(output_path, 'w') as f:
    f.write(thesis_document)

print(f"Thesis document written to: {output_path}")
print()

# =============================================================================
# 10. SUMMARY METRICS FOR QUICK REFERENCE
# =============================================================================
print("=" * 60)
print("QUICK REFERENCE SUMMARY")
print("=" * 60)

summary = {
    'ticker': 'CHGG',
    'current_price': current_price,
    'market_cap_m': market_cap,
    'enterprise_value_m': enterprise_value,
    'ttm_revenue_m': ttm_revenue,
    'revenue_growth_pct': revenue_growth * 100,
    'decline_from_peak_pct': decline_from_peak,
    'normalized_ebitda_m': ebitda,
    'r&d_as_pct_revenue': avg_rd_pct,
    'short_interest_pct': short_pct_float,
    'days_to_cover': short_ratio,
    'entry_low': entry_range_low,
    'entry_high': entry_range_high,
    'stop_loss': stop_loss,
    'target_base': target_base,
    'target_bear': target_bear,
    'target_extreme': target_extreme,
    'risk_reward_ratio': f"1:{reward_base/risk:.1f}",
    'privatization_floor': buyout_df[buyout_df['Multiple']==3]['Implied_Price'].values[0],
    'privatization_fair': buyout_df[buyout_df['Multiple']==5]['Implied_Price'].values[0],
    'generated_at': datetime.now().isoformat()
}

print(f"Ticker: {summary['ticker']}")
print(f"Current Price: ${summary['current_price']:.2f}")
print(f"Entry Zone: ${summary['entry_low']:.2f} - ${summary['entry_high']:.2f}")
print(f"Stop Loss: ${summary['stop_loss']:.2f}")
print(f"Target 1 (Base): ${summary['target_base']:.2f}")
print(f"Target 2 (Bear): ${summary['target_bear']:.2f}")
print(f"Risk/Reward: {summary['risk_reward_ratio']}")
print()

# Save summary JSON for downstream use
summary_path = RESULTS_DIR / 'thesis_summary.json'
with open(summary_path, 'w') as f:
    json.dump(summary, f, indent=2)

print(f"Summary JSON written to: {summary_path}")
print()

print("=" * 80)
print("STEP 5 COMPLETE: Investment Thesis & Risk Assessment")
print("=" * 80)
print(f"Generated artifacts:")
print(f"  1. {output_path}")
print(f"  2. {summary_path}")
