#!/usr/bin/env python3
"""
VK2735 Valuation & Expectation Modeling
========================================
Step 3 of the Viking Therapeutics Investment Analysis

This script builds a financial model to:
1. Estimate VK2735's peak sales potential
2. Calculate Risk-Adjusted Net Present Value (rNPV)
3. Reverse-engineer market expectations from current ~$6B market cap

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

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

# =============================================================================
# CONFIGURATION
# =============================================================================
SESSION_DIR = Path("/app/sandbox/session_20260203_085220_b017de51c5a6")
DATA_DIR = SESSION_DIR / "data"
RESULTS_DIR = SESSION_DIR / "results"

# Ensure directories exist
DATA_DIR.mkdir(exist_ok=True)
RESULTS_DIR.mkdir(exist_ok=True)

print("=" * 70)
print("VK2735 VALUATION & EXPECTATION MODELING")
print("=" * 70)

# =============================================================================
# 1. MARKET SIZING & PRICING ASSUMPTIONS
# =============================================================================
print("\n[1/5] Establishing Market Sizing & Pricing Assumptions...")

# US Obesity Market Parameters
US_ADULT_POPULATION = 260_000_000  # ~260M US adults
OBESITY_PREVALENCE = 0.42  # ~42% obesity rate (BMI >= 30)
SEVERE_OBESITY_PREVALENCE = 0.09  # ~9% severe obesity (BMI >= 40)

# GLP-1 Market Parameters (2024-2030 projections)
GLP1_MARKET_2024 = 53.46e9  # $53.46B global market
GLP1_MARKET_2030 = 156.71e9  # $156.71B projected
US_MARKET_SHARE_GLOBAL = 0.77  # US = 77% of global GLP-1 revenue

# VK2735 Specific Assumptions
LAUNCH_YEAR = 2028
PATENT_EXPIRY_YEAR = 2040  # Estimated patent life
DISCOUNT_RATE = 0.11  # 11% (biotech industry standard)
TAX_RATE = 0.21  # US corporate tax rate
COGS_MARGIN = 0.15  # Cost of goods sold as % of revenue
SGA_MARGIN = 0.30  # SG&A as % of revenue (launch and marketing)

# Net Pricing (after rebates, based on Wegovy/Zepbound)
NET_PRICE_LOW = 6500  # Conservative
NET_PRICE_BASE = 7250  # Base case
NET_PRICE_HIGH = 8000  # Optimistic

# Market Share Scenarios (% of addressable GLP-1 obesity market)
MARKET_SHARE_SCENARIOS = {
    'Conservative': 0.05,  # 5%
    'Base': 0.10,          # 10%
    'Optimistic': 0.15     # 15%
}

# Current Viking Therapeutics Market Cap
CURRENT_MARKET_CAP = 6.0e9  # ~$6 billion

# Probability of Success ranges for Phase 3
POS_RANGE = np.arange(0.50, 0.95, 0.05)  # 50% to 90%

print(f"  - US Adult Population: {US_ADULT_POPULATION:,}")
print(f"  - Obesity Prevalence: {OBESITY_PREVALENCE:.0%}")
print(f"  - Addressable Population: {int(US_ADULT_POPULATION * OBESITY_PREVALENCE):,}")
print(f"  - GLP-1 Market 2024: ${GLP1_MARKET_2024/1e9:.1f}B global")
print(f"  - GLP-1 Market 2030 (projected): ${GLP1_MARKET_2030/1e9:.1f}B global")
print(f"  - US Share of Global Market: {US_MARKET_SHARE_GLOBAL:.0%}")
print(f"  - Launch Year: {LAUNCH_YEAR}")
print(f"  - Patent Expiry: {PATENT_EXPIRY_YEAR}")
print(f"  - Discount Rate: {DISCOUNT_RATE:.0%}")
print(f"  - Net Price Range: ${NET_PRICE_LOW:,} - ${NET_PRICE_HIGH:,}/year")

# =============================================================================
# 2. rNPV MODEL FUNCTIONS
# =============================================================================
print("\n[2/5] Building rNPV Model...")

def calculate_peak_sales(market_share: float, net_price: float, year: int = 2030) -> float:
    """
    Calculate peak sales based on market share and pricing assumptions.

    Parameters
    ----------
    market_share : float
        VK2735's share of the GLP-1 obesity market (e.g., 0.10 for 10%)
    net_price : float
        Annual net price per patient
    year : int
        Target year for market size calculation

    Returns
    -------
    float
        Peak annual sales in dollars
    """
    # Interpolate/extrapolate US GLP-1 market size
    if year <= 2024:
        us_market = GLP1_MARKET_2024 * US_MARKET_SHARE_GLOBAL
    elif year >= 2030:
        us_market = GLP1_MARKET_2030 * US_MARKET_SHARE_GLOBAL
    else:
        # Linear interpolation
        growth_rate = (GLP1_MARKET_2030 / GLP1_MARKET_2024) ** (1/6)
        years_from_2024 = year - 2024
        us_market = GLP1_MARKET_2024 * US_MARKET_SHARE_GLOBAL * (growth_rate ** years_from_2024)

    return us_market * market_share


def generate_revenue_curve(peak_sales: float, launch_year: int,
                           patent_expiry: int, ramp_years: int = 4) -> dict:
    """
    Generate annual revenue curve from launch to patent expiry.

    Assumes:
    - 4-year ramp to peak sales
    - Peak sales maintained until 2 years before patent expiry
    - 50% decline in final 2 years due to genericization anticipation
    """
    revenues = {}
    years_to_peak = ramp_years

    for year in range(launch_year, patent_expiry + 1):
        years_since_launch = year - launch_year

        if years_since_launch < years_to_peak:
            # Ramp phase: S-curve growth
            ramp_factor = (years_since_launch + 1) / years_to_peak
            revenue = peak_sales * (ramp_factor ** 1.5)  # Accelerating growth
        elif year >= patent_expiry - 1:
            # Generic erosion phase
            years_to_expiry = patent_expiry - year
            erosion_factor = 0.5 + 0.25 * years_to_expiry
            revenue = peak_sales * erosion_factor
        else:
            # Peak phase
            revenue = peak_sales

        revenues[year] = revenue

    return revenues


def calculate_rnpv(peak_sales: float, prob_success: float,
                   launch_year: int = LAUNCH_YEAR,
                   patent_expiry: int = PATENT_EXPIRY_YEAR,
                   discount_rate: float = DISCOUNT_RATE,
                   tax_rate: float = TAX_RATE) -> dict:
    """
    Calculate Risk-Adjusted Net Present Value.

    Returns
    -------
    dict
        Contains rNPV, NPV, and intermediate calculations
    """
    current_year = 2026

    # Generate revenue projections
    revenues = generate_revenue_curve(peak_sales, launch_year, patent_expiry)

    # Calculate operating income and free cash flow
    total_npv = 0
    annual_data = []

    for year, revenue in revenues.items():
        # Operating expenses
        cogs = revenue * COGS_MARGIN
        sga = revenue * SGA_MARGIN
        operating_income = revenue - cogs - sga

        # Tax
        taxes = operating_income * tax_rate if operating_income > 0 else 0
        net_income = operating_income - taxes

        # Discount factor
        years_out = year - current_year
        discount_factor = 1 / ((1 + discount_rate) ** years_out)

        # Present value
        pv = net_income * discount_factor
        total_npv += pv

        annual_data.append({
            'Year': year,
            'Revenue': revenue,
            'Operating_Income': operating_income,
            'Net_Income': net_income,
            'Discount_Factor': discount_factor,
            'Present_Value': pv
        })

    # Risk adjustment
    rnpv = total_npv * prob_success

    return {
        'rNPV': rnpv,
        'NPV': total_npv,
        'Peak_Sales': peak_sales,
        'Prob_Success': prob_success,
        'Launch_Year': launch_year,
        'Patent_Expiry': patent_expiry,
        'Annual_Data': annual_data
    }


print("  - Revenue curve generator: S-curve ramp (4 years), peak maintenance, generic erosion")
print("  - Operating margin: ~55% (after COGS and SG&A)")
print("  - Discount rate: 11%")
print("  - Tax rate: 21%")

# =============================================================================
# 3. SCENARIO MATRIX GENERATION
# =============================================================================
print("\n[3/5] Generating Valuation Scenario Matrix...")

# Generate all scenarios
scenarios = []
peak_sales_values = []

# First, calculate peak sales for each market share scenario
for scenario_name, market_share in MARKET_SHARE_SCENARIOS.items():
    for price_label, net_price in [('Low', NET_PRICE_LOW), ('Base', NET_PRICE_BASE), ('High', NET_PRICE_HIGH)]:
        peak = calculate_peak_sales(market_share, net_price, year=2030)
        peak_sales_values.append({
            'Scenario': f"{scenario_name}_{price_label}",
            'Market_Share': market_share,
            'Net_Price': net_price,
            'Peak_Sales_B': peak / 1e9
        })

peak_sales_df = pd.DataFrame(peak_sales_values)
print("\nPeak Sales Scenarios (at 2030 market size):")
print(peak_sales_df.to_string(index=False))

# Generate rNPV for each combination
scenario_results = []
for scenario_name, market_share in MARKET_SHARE_SCENARIOS.items():
    peak = calculate_peak_sales(market_share, NET_PRICE_BASE, year=2030)

    for pos in POS_RANGE:
        result = calculate_rnpv(peak, pos)
        scenario_results.append({
            'Scenario': scenario_name,
            'Market_Share_Pct': market_share * 100,
            'Peak_Sales_B': peak / 1e9,
            'PoS_Pct': pos * 100,
            'NPV_B': result['NPV'] / 1e9,
            'rNPV_B': result['rNPV'] / 1e9
        })

        if int(pos * 100) % 10 == 0:
            print(f"  Processing: {scenario_name} @ PoS={pos:.0%} -> rNPV=${result['rNPV']/1e9:.2f}B")

scenarios_df = pd.DataFrame(scenario_results)

# Save to CSV
scenarios_csv_path = DATA_DIR / "valuation_scenarios.csv"
scenarios_df.to_csv(scenarios_csv_path, index=False)
print(f"\nSaved scenarios to: {scenarios_csv_path}")

# =============================================================================
# 4. REVERSE ENGINEERING ANALYSIS
# =============================================================================
print("\n[4/5] Reverse Engineering Market Expectations...")

# Question 1: What PoS is implied at Base Case peak sales for $6B valuation?
base_case_peak = calculate_peak_sales(MARKET_SHARE_SCENARIOS['Base'], NET_PRICE_BASE, year=2030)
base_npv_result = calculate_rnpv(base_case_peak, prob_success=1.0)
base_npv = base_npv_result['NPV']

implied_pos_at_base = CURRENT_MARKET_CAP / base_npv
print(f"\n  Base Case Peak Sales: ${base_case_peak/1e9:.2f}B")
print(f"  Base Case NPV (100% PoS): ${base_npv/1e9:.2f}B")
print(f"  Current Market Cap: ${CURRENT_MARKET_CAP/1e9:.1f}B")
print(f"  IMPLIED PoS (at Base Case): {implied_pos_at_base:.1%}")

# Question 2: What peak sales are implied at standard biotech PoS (65%)?
standard_pos = 0.65
# rNPV = NPV * PoS, so NPV_required = Market_Cap / PoS
implied_npv_required = CURRENT_MARKET_CAP / standard_pos

# We need to find peak sales that gives this NPV
# Binary search for peak sales
def find_peak_sales_for_npv(target_npv, tolerance=0.01e9):
    low, high = 1e9, 20e9
    while high - low > tolerance:
        mid = (low + high) / 2
        result = calculate_rnpv(mid, 1.0)
        if result['NPV'] < target_npv:
            low = mid
        else:
            high = mid
    return mid

implied_peak_sales = find_peak_sales_for_npv(implied_npv_required)
print(f"\n  At Standard Biotech PoS ({standard_pos:.0%}):")
print(f"  Required NPV: ${implied_npv_required/1e9:.2f}B")
print(f"  IMPLIED Peak Sales Required: ${implied_peak_sales/1e9:.2f}B")

# Calculate what market share this implies
implied_market_share = implied_peak_sales / (GLP1_MARKET_2030 * US_MARKET_SHARE_GLOBAL)
print(f"  Implied Market Share: {implied_market_share:.1%}")

# Question 3: Sensitivity table
print("\n  Generating Implied Expectations Matrix...")
implied_expectations = []
for peak_label, peak_mult in [('Conservative ($3B)', 3e9), ('Base ($6B)', 6e9),
                               ('Optimistic ($9B)', 9e9), ('Blockbuster ($12B)', 12e9)]:
    result_100 = calculate_rnpv(peak_mult, 1.0)
    npv = result_100['NPV']
    implied_pos = CURRENT_MARKET_CAP / npv if npv > 0 else float('inf')
    implied_expectations.append({
        'Peak_Sales_Assumption': peak_label,
        'Peak_Sales_B': peak_mult / 1e9,
        'NPV_B': npv / 1e9,
        'Implied_PoS_Pct': min(implied_pos * 100, 100)
    })

implied_df = pd.DataFrame(implied_expectations)
print("\nImplied Probability of Success (to justify $6B market cap):")
print(implied_df.to_string(index=False))

# =============================================================================
# 5. COMPARABLE TRANSACTION ANALYSIS
# =============================================================================
print("\n[5/5] Comparable Transaction Analysis...")

comparables = [
    {
        'Transaction': 'Roche-Carmot (Dec 2023)',
        'Upfront_B': 2.7,
        'Milestones_B': 0.4,
        'Total_B': 3.1,
        'Stage': 'Phase 2 ready',
        'Assets': 'CT-388 (GLP-1/GIP), CT-996 (oral GLP-1), CT-868',
        'Notes': 'Dual agonist, strong Phase 1b data (18.8% weight loss)'
    },
    {
        'Transaction': 'Viking Therapeutics (Current)',
        'Upfront_B': 6.0,  # Market cap as proxy
        'Milestones_B': 0.0,
        'Total_B': 6.0,
        'Stage': 'Phase 2 complete',
        'Assets': 'VK2735 (GLP-1/GIP SC + Oral)',
        'Notes': 'Phase 2b: 14.7% weight loss (13wk), oral 8.2%'
    }
]

comp_df = pd.DataFrame(comparables)
print("\nComparable Transactions:")
print(comp_df[['Transaction', 'Upfront_B', 'Stage', 'Notes']].to_string(index=False))

# Valuation premium analysis
carmot_value = 3.1e9
viking_value = 6.0e9
premium = (viking_value / carmot_value - 1) * 100
print(f"\n  Viking Premium vs. Carmot: +{premium:.0f}%")
print("  Justification factors:")
print("    - VK2735 Phase 2 complete (vs Phase 2-ready)")
print("    - Strong subcutaneous data competitive with Zepbound")
print("    - Public market premium (liquidity)")
print("    - However: Carmot oral GLP-1 (CT-996) showed 7.3% weight loss vs VK2735 oral 8.2%")

# =============================================================================
# 6. GENERATE SUMMARY REPORT
# =============================================================================
print("\n" + "=" * 70)
print("GENERATING VALUATION ANALYSIS REPORT")
print("=" * 70)

summary_md = f"""# VK2735 Valuation & Expectation Analysis

## Executive Summary

This analysis models VK2735's valuation potential and reverse-engineers what Viking Therapeutics' ~$6B market capitalization implies about market expectations.

**Key Finding**: The current $6B market cap implies the market is pricing in a **{implied_pos_at_base:.0%} probability of success** assuming Base Case peak sales of ~${base_case_peak/1e9:.1f}B. Alternatively, at a standard biotech Phase 3 PoS of 65%, the market implies peak sales of ~${implied_peak_sales/1e9:.1f}B.

---

## 1. Market Sizing & Pricing Assumptions

### US Obesity Market
| Parameter | Value | Source |
|-----------|-------|--------|
| US Adult Population | {US_ADULT_POPULATION:,} | Census Bureau |
| Obesity Prevalence | {OBESITY_PREVALENCE:.0%} | CDC (BMI ≥ 30) |
| Addressable Population | {int(US_ADULT_POPULATION * OBESITY_PREVALENCE):,} | Calculated |

### GLP-1 Market Projections
| Metric | 2024 | 2030 (Projected) |
|--------|------|------------------|
| Global GLP-1 Market | ${GLP1_MARKET_2024/1e9:.1f}B | ${GLP1_MARKET_2030/1e9:.1f}B |
| US Share | {US_MARKET_SHARE_GLOBAL:.0%} | {US_MARKET_SHARE_GLOBAL:.0%} |
| US GLP-1 Market | ${GLP1_MARKET_2024 * US_MARKET_SHARE_GLOBAL/1e9:.1f}B | ${GLP1_MARKET_2030 * US_MARKET_SHARE_GLOBAL/1e9:.1f}B |

### Net Pricing Assumptions
Based on Zepbound and Wegovy benchmark pricing:
- **Conservative**: ${NET_PRICE_LOW:,}/patient/year
- **Base Case**: ${NET_PRICE_BASE:,}/patient/year
- **Optimistic**: ${NET_PRICE_HIGH:,}/patient/year

---

## 2. Peak Sales Scenarios

| Scenario | Market Share | Peak Sales (2030) |
|----------|--------------|-------------------|
| Conservative | 5% | ${calculate_peak_sales(0.05, NET_PRICE_BASE)/1e9:.1f}B |
| Base Case | 10% | ${calculate_peak_sales(0.10, NET_PRICE_BASE)/1e9:.1f}B |
| Optimistic | 15% | ${calculate_peak_sales(0.15, NET_PRICE_BASE)/1e9:.1f}B |

---

## 3. rNPV Model Parameters

| Parameter | Value | Rationale |
|-----------|-------|-----------|
| Launch Year | {LAUNCH_YEAR} | Assumes Phase 3 initiation 2025, 2-3 year trial |
| Patent Expiry | {PATENT_EXPIRY_YEAR} | Estimated composition of matter + extensions |
| Discount Rate | {DISCOUNT_RATE:.0%} | Biotech industry standard |
| Tax Rate | {TAX_RATE:.0%} | US corporate rate |
| COGS | {COGS_MARGIN:.0%} | Biologics manufacturing |
| SG&A | {SGA_MARGIN:.0%} | Launch and marketing |

---

## 4. Reverse Engineering: What Is the Market Pricing In?

### Current Valuation
- **Viking Therapeutics Market Cap**: ~${CURRENT_MARKET_CAP/1e9:.1f}B

### Scenario A: Implied Probability of Success

Assuming **Base Case peak sales of ${base_case_peak/1e9:.1f}B**:
- NPV at 100% PoS: ${base_npv/1e9:.1f}B
- **Implied PoS to justify $6B: {implied_pos_at_base:.0%}**

| Peak Sales Assumption | NPV (100% PoS) | Implied PoS for $6B |
|-----------------------|----------------|---------------------|
"""

for row in implied_expectations:
    pos_display = f"{row['Implied_PoS_Pct']:.0f}%" if row['Implied_PoS_Pct'] <= 100 else ">100%"
    summary_md += f"| {row['Peak_Sales_Assumption']} | ${row['NPV_B']:.1f}B | {pos_display} |\n"

summary_md += f"""
### Scenario B: Implied Peak Sales

Assuming **standard Phase 3 PoS of 65%**:
- Required NPV: ${implied_npv_required/1e9:.1f}B
- **Implied Peak Sales: ${implied_peak_sales/1e9:.1f}B**
- Implied Market Share: {implied_market_share:.1%}

---

## 5. Comparable Transaction Analysis

### Roche-Carmot Therapeutics (December 2023)
- **Deal Value**: $2.7B upfront + $0.4B milestones = **$3.1B total**
- **Stage**: Phase 2-ready
- **Assets**: CT-388 (GLP-1/GIP dual agonist), CT-996 (oral GLP-1), CT-868
- **Clinical Data**: CT-388 showed 18.8% placebo-adjusted weight loss (24 weeks, Phase 1b)

### Viking Therapeutics Comparison
- **Current Market Cap**: ~$6.0B
- **Stage**: Phase 2 complete
- **Assets**: VK2735 (SC + Oral formulations)
- **Clinical Data**: SC showed 14.7% weight loss (13 weeks); Oral showed 8.2% (28 days)

### Valuation Premium Analysis
Viking trades at a **{premium:.0f}% premium** to the Carmot deal value. This may be justified by:

1. **More Advanced Development**: Phase 2 complete vs. Phase 2-ready
2. **Strong Subcutaneous Data**: 14.7% weight loss competitive with Zepbound
3. **Public Market Liquidity**: Premium for publicly traded equity
4. **Dual Formulation Strategy**: Both injectable and oral in development

However, the premium is partially offset by:
- Carmot's CT-996 oral data (7.3% weight loss) comparable to VK2735 oral (8.2%)
- Roche's deep pockets and manufacturing capabilities post-acquisition
- VK2735 oral tolerability concerns (28% discontinuation from GI events)

---

## 6. Investment Implications

### Bull Case: Market Correctly Pricing VK2735
- Phase 3 success leads to $8-10B peak sales
- Implied PoS of ~50% is conservative given strong Phase 2 data
- Partnership/acquisition premium potential

### Bear Case: Overvaluation Risk
- Market assuming optimistic peak sales ($9B+)
- Standard Phase 3 PoS (~65%) would require $9.2B peak sales
- VK2735 oral formulation challenges may limit market differentiation
- Competitive pressure from Lilly, Novo, Roche pipeline

### Key Metrics to Monitor
1. **Phase 3 Trial Design**: Primary endpoint, trial size, timeline
2. **Oral Formulation Strategy**: Path forward for oral VK2735
3. **Manufacturing Readiness**: CMO partnerships, capacity commitments
4. **Partnership Discussions**: Any announced licensing/acquisition talks

---

## Data Sources

- Market sizing: [Evaluate GLP-1 Report](https://www.evaluate.com/thought-leadership/obesity-and-glp-1-dealmaking-strategic-trends-and-market-signals/)
- Carmot deal: [BioPharma Dive](https://www.biopharmadive.com/news/roche-carmot-acquire-deal-obesity-drug/701383/)
- Clinical data: Viking Therapeutics investor presentations and SEC filings

---

*Analysis generated by K-Dense on {pd.Timestamp.now().strftime('%Y-%m-%d')}*
"""

# Save the summary report
summary_path = RESULTS_DIR / "valuation_analysis.md"
with open(summary_path, 'w') as f:
    f.write(summary_md)
print(f"Saved analysis report to: {summary_path}")

# =============================================================================
# FINAL SUMMARY
# =============================================================================
print("\n" + "=" * 70)
print("EXECUTION COMPLETE")
print("=" * 70)
print(f"""
Key Findings:
-------------
1. Base Case Peak Sales: ${base_case_peak/1e9:.1f}B (10% market share at base pricing)
2. Implied PoS at Base Case: {implied_pos_at_base:.0%}
3. Implied Peak Sales at 65% PoS: ${implied_peak_sales/1e9:.1f}B
4. Viking vs Carmot Premium: +{premium:.0f}%

Files Generated:
----------------
- {scenarios_csv_path}
- {summary_path}
""")
