#!/usr/bin/env python3
"""
Step 4: Patent Cliff Timing Analysis
=====================================
Analyzes patent expiration dates for GLP-1 competitor drugs to assess
the competitive landscape and "Premium Pricing Window" for VK2735.

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

import pandas as pd
from datetime import datetime
import os

print("=" * 60)
print("Step 4: Patent Cliff Timing Analysis")
print("=" * 60)

# Define session directory
SESSION_DIR = "/app/sandbox/session_20260203_085220_b017de51c5a6"

# =============================================================================
# 1. PATENT LANDSCAPE DATA
# =============================================================================
print("\n[1/4] Compiling patent landscape data...")

# Based on extensive research from IQVIA, I-MAK, GreyB, DrugPatentWatch,
# and other authoritative patent sources

patent_data = [
    {
        "Drug": "Semaglutide (Ozempic/Wegovy)",
        "Company": "Novo Nordisk",
        "Indication": "T2DM / Obesity",
        "Base_Patent_Expiry_US": "2026-03-20",  # US 8,536,122
        "Estimated_LOE_US": "2032-01-01",  # With PTA/PTE extensions
        "Base_Patent_Expiry_EU": "2026-03-20",
        "Estimated_LOE_EU": "2026-03-20",  # No SPC extension confirmed
        "Key_Patent_Numbers": "US 8,129,343; US 8,536,122",
        "Extension_Type": "PTA + PTE (5+ years)",
        "Notes": "Main compound patent extended to Dec 2031 via PTA/PTE. Follow-on patents for Wegovy extend to ~2040. Generic entry US expected 2032. International (Canada, India, China) 2026."
    },
    {
        "Drug": "Tirzepatide (Mounjaro/Zepbound)",
        "Company": "Eli Lilly",
        "Indication": "T2DM / Obesity",
        "Base_Patent_Expiry_US": "2036-01-05",  # Main compound patent
        "Estimated_LOE_US": "2039-07-22",  # Zepbound; Mounjaro potentially 2041
        "Base_Patent_Expiry_EU": "2036-01-05",
        "Estimated_LOE_EU": "2036-01-05",  # Estimated
        "Key_Patent_Numbers": "Multiple (6 patents filed)",
        "Extension_Type": "Follow-on patents to 2041",
        "Notes": "Main compound expires 2036. Follow-on patents (formulation, devices, methods) extend to 2041. Zepbound generic entry ~Jul 2039, Mounjaro ~Dec 2041."
    },
    {
        "Drug": "VK2735",
        "Company": "Viking Therapeutics",
        "Indication": "Obesity (Phase 3)",
        "Base_Patent_Expiry_US": "2040-01-01",  # Estimated from typical 20-year patent from filing
        "Estimated_LOE_US": "2043-01-01",  # Estimated with potential extensions
        "Base_Patent_Expiry_EU": "2040-01-01",
        "Estimated_LOE_EU": "2040-01-01",
        "Key_Patent_Numbers": "Pending (Phase 3 asset)",
        "Extension_Type": "Estimated (PTE likely)",
        "Notes": "Phase 3 dual agonist (GLP-1/GIP). Patents filed ~2020. Projected launch 2028. Est. patent life to 2040+."
    }
]

# Create DataFrame
df_patents = pd.DataFrame(patent_data)
print(f"  Compiled patent data for {len(df_patents)} drugs")

# =============================================================================
# 2. TIMELINE CONSTRUCTION
# =============================================================================
print("\n[2/4] Constructing patent timeline...")

# Key timeline dates
timeline_events = {
    "VK2735_Launch": "2028-01-01",  # Projected FDA approval/launch
    "Semaglutide_Intl_Generic": "2026-03-20",  # International generics
    "Semaglutide_US_Generic": "2032-01-01",  # US generic entry
    "Tirzepatide_US_Generic": "2039-07-22",  # Zepbound generic (conservative)
    "VK2735_Patent_Expiry": "2040-01-01",  # Estimated
    "Semaglutide_FollowOn_Expiry": "2040-01-01",  # Wegovy follow-on
    "Tirzepatide_FollowOn_Expiry": "2041-12-30",  # Mounjaro follow-on
    "VK2735_Potential_PTE": "2043-01-01",  # With potential extensions
}

# Convert to datetime
for key in timeline_events:
    timeline_events[key] = datetime.strptime(timeline_events[key], "%Y-%m-%d")

vk2735_launch = timeline_events["VK2735_Launch"]
print(f"  VK2735 projected launch: {vk2735_launch.strftime('%Y-%m-%d')}")

# =============================================================================
# 3. GENERIC THREAT WINDOW ANALYSIS
# =============================================================================
print("\n[3/4] Analyzing Generic Threat Windows...")

# Calculate premium pricing window for VK2735
semaglutide_us_generic = timeline_events["Semaglutide_US_Generic"]
tirzepatide_us_generic = timeline_events["Tirzepatide_US_Generic"]
vk2735_patent = timeline_events["VK2735_Patent_Expiry"]

# Years from VK2735 launch to competitor generics
years_to_sema_generic = (semaglutide_us_generic - vk2735_launch).days / 365.25
years_to_tirze_generic = (tirzepatide_us_generic - vk2735_launch).days / 365.25
years_of_vk2735_patent = (vk2735_patent - vk2735_launch).days / 365.25

print(f"  Years from VK2735 launch to Semaglutide generics: {years_to_sema_generic:.1f} years")
print(f"  Years from VK2735 launch to Tirzepatide generics: {years_to_tirze_generic:.1f} years")
print(f"  VK2735 patent-protected period from launch: {years_of_vk2735_patent:.1f} years")

# International considerations
semaglutide_intl = timeline_events["Semaglutide_Intl_Generic"]
years_sema_intl_before_launch = (vk2735_launch - semaglutide_intl).days / 365.25

print(f"\n  Semaglutide international generics: {semaglutide_intl.strftime('%Y-%m-%d')}")
print(f"  Years before VK2735 launch (intl market): {years_sema_intl_before_launch:.1f} years")

# =============================================================================
# 4. STRATEGIC IMPLICATIONS
# =============================================================================
print("\n[4/4] Determining strategic implications...")

analysis_summary = {
    "Premium_Pricing_Window_Years": round(years_to_sema_generic, 1),
    "Full_Brand_Premium_Window_Years": round(years_to_tirze_generic, 1),
    "VK2735_Patent_Protection_Years": round(years_of_vk2735_patent, 1),
    "First_Generic_Threat": "Semaglutide (2032)",
    "Second_Generic_Threat": "Tirzepatide (2039)",
    "VK2735_Launch_Year": 2028,
    "Semaglutide_LOE_Year": 2032,
    "Tirzepatide_LOE_Year": 2039,
    "VK2735_LOE_Year": 2040
}

print(f"\n  PREMIUM PRICING WINDOW SUMMARY:")
print(f"  --------------------------------")
print(f"  VK2735 has ~{analysis_summary['Premium_Pricing_Window_Years']} years of premium pricing")
print(f"  before Semaglutide generics enter the US market.")
print(f"  ")
print(f"  Full brand-vs-brand competition (no generics) lasts")
print(f"  ~{analysis_summary['Full_Brand_Premium_Window_Years']} years (until Tirzepatide generics).")

# =============================================================================
# 5. SAVE OUTPUTS
# =============================================================================
print("\n" + "=" * 60)
print("Saving outputs...")

# Save patent landscape CSV
csv_path = os.path.join(SESSION_DIR, "data", "patent_landscape.csv")
df_patents.to_csv(csv_path, index=False)
print(f"  ✓ Saved: {csv_path}")

# Create comprehensive analysis markdown
md_content = f"""# Patent Cliff Timing Analysis

## Executive Summary

Viking Therapeutics' VK2735 is positioned to launch in **2028**, entering a GLP-1 market with a
favorable patent landscape. The analysis reveals a **{analysis_summary['Premium_Pricing_Window_Years']:.0f}-year premium pricing window**
before the first major generic threat (Semaglutide) in the US market.

---

## 1. Patent Landscape Overview

| Drug | Company | Base Patent Expiry (US) | Estimated LOE (US) | Notes |
|------|---------|------------------------|-------------------|-------|
| Semaglutide (Ozempic/Wegovy) | Novo Nordisk | March 2026 | **January 2032** | Extended via PTA/PTE |
| Tirzepatide (Mounjaro/Zepbound) | Eli Lilly | January 2036 | **July 2039** | Follow-on patents to 2041 |
| VK2735 | Viking Therapeutics | Est. 2040 | **Est. 2040-2043** | Phase 3 asset |

### Key Patent Details

#### Semaglutide (Novo Nordisk)
- **Core Patents**: US 8,129,343 and US 8,536,122 (filed March 2006)
- **Base Expiry**: March 20, 2026
- **Extended Expiry**: December 5, 2031 (via Patent Term Adjustment + Patent Term Extension)
- **US Generic Entry**: Expected **January 2032**
- **International**: Generics available in Canada, India, China, Brazil from **March 2026**
- **Follow-on Patents**: Wegovy formulation/device patents extend to ~2040

#### Tirzepatide (Eli Lilly)
- **Core Patents**: 6 patents filed (2024-2025)
- **Base Expiry**: January 5, 2036
- **Follow-on Patents**: Extend protection to December 2041
- **Zepbound Generic Entry**: Expected **July 2039**
- **Mounjaro Generic Entry**: Expected **December 2041** (latest estimate)

#### VK2735 (Viking Therapeutics)
- **Status**: Phase 3 clinical trials
- **Patent Filing**: ~2020 (estimated)
- **Estimated Expiry**: 2040 (base) to 2043 (with potential PTE)
- **Projected Launch**: 2028

---

## 2. Premium Pricing Window Analysis

### Timeline Visualization

```
2026  2027  2028  2029  2030  2031  2032  2033  2034  2035  2036  2037  2038  2039  2040  2041
  |     |     |     |     |     |     |     |     |     |     |     |     |     |     |     |
  |     |    VK2735 LAUNCH                    |                                    |     |
  |     |     █══════════════════════════════█|════════════════════════════════════█     |
  |     |     |<-- Premium Pricing Window -->|                                     |     |
  |     |     |         (~4 years)           |                                     |     |
  |     |     |                              |                                     |     |
SEMA   |     |                         SEMA US                              TIRZE US     |
INTL   |     |                         GENERIC                              GENERIC     VK2735
GEN    |     |                              |                                     |    LOE
  |     |     |                              |                                     |     |
```

### Key Metrics

| Metric | Value | Interpretation |
|--------|-------|----------------|
| **Premium Pricing Window** | **{analysis_summary['Premium_Pricing_Window_Years']:.1f} years** | Years from VK2735 launch until Semaglutide generics (first price shock) |
| **Full Brand Competition Window** | **{analysis_summary['Full_Brand_Premium_Window_Years']:.1f} years** | Years from launch until Tirzepatide generics |
| **VK2735 Patent Protection** | **{analysis_summary['VK2735_Patent_Protection_Years']:.1f} years** | Years of patent protection from launch |
| **First Generic Threat** | Semaglutide | Expected January 2032 |
| **Second Generic Threat** | Tirzepatide | Expected July 2039 |

---

## 3. Strategic Implications

### ✅ Favorable Factors for Viking

1. **4-Year Head Start**: VK2735 launches in 2028, giving Viking ~4 years of brand-only competition
   in the US before Semaglutide generics enter in 2032.

2. **Differentiation Window**: The 4-year window allows Viking to establish market presence,
   brand recognition, and demonstrate differentiated efficacy before generic price erosion.

3. **Tirzepatide Protection**: Viking faces no generic Tirzepatide competition until 2039,
   providing ~11 years of brand-vs-brand competition.

4. **Superior Efficacy Positioning**: VK2735's clinical data (up to 14.7% weight loss at 13 weeks)
   may command premium pricing even after Semaglutide generics enter.

### ⚠️ Risk Factors

1. **International Generic Pressure (2026)**: Semaglutide generics will be available in major
   international markets (Canada, India, China) from March 2026 - 2 years before VK2735 launch.
   - This may establish generic pricing expectations
   - Could enable international price referencing pressure

2. **Post-2032 Price Erosion**: After Semaglutide generics enter the US:
   - Market price benchmarks will shift downward
   - VK2735 will need strong differentiation to maintain premium
   - Payers may require greater rebates

3. **Regulatory Timeline Risk**: Any delay in VK2735 approval shortens the premium window.

---

## 4. Competitive Timeline Summary

| Year | Event | Impact on VK2735 |
|------|-------|------------------|
| 2026 | Semaglutide international generics | Price reference pressure in ex-US markets |
| 2028 | **VK2735 US Launch** | **Market entry into brand-dominated market** |
| 2032 | Semaglutide US generics | First price shock; ~4 years post-launch |
| 2039 | Tirzepatide US generics | Second price shock; ~11 years post-launch |
| 2040 | VK2735 base patent expiry | Viking's own generic risk begins |
| 2041 | Tirzepatide follow-on expiry | Full generic competition across GLP-1 class |

---

## 5. Conclusions

**Bottom Line**: Viking Therapeutics has a **strategically favorable patent cliff timing position**.

- **Premium Pricing Window**: ~4 years (2028-2032) before Semaglutide generics
- **Extended Brand Window**: ~11 years (2028-2039) before Tirzepatide generics
- **Own Patent Life**: ~12 years of protection from launch (to 2040+)

The ~4-year premium window is sufficient for Viking to:
1. Establish market presence and formulary positioning
2. Generate meaningful revenue to fund pipeline
3. Demonstrate differentiated efficacy and safety profile
4. Build brand loyalty before generic alternatives emerge

**Recommendation**: The patent cliff analysis supports a 2028 launch target. Viking should
prioritize expedited approval pathways to maximize the premium pricing window.

---

## Data Sources

- IQVIA: "Off-patent semaglutide in 2026"
- I-MAK: "The Heavy Price of GLP-1 Drugs"
- GreyB: Mounjaro patent expiration analysis
- DrugPatentWatch: ZEPBOUND and MOUNJARO patent data
- Markman Advisors: Semaglutide patent landscape analysis
- Drugs.com: Generic availability timelines

---

*Analysis generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}*
"""

# Save analysis markdown
md_path = os.path.join(SESSION_DIR, "results", "patent_cliff_analysis.md")
with open(md_path, 'w') as f:
    f.write(md_content)
print(f"  ✓ Saved: {md_path}")

# =============================================================================
# EXECUTION SUMMARY
# =============================================================================
print("\n" + "=" * 60)
print("PATENT CLIFF ANALYSIS COMPLETE")
print("=" * 60)
print(f"""
KEY FINDINGS:
─────────────
• VK2735 Premium Pricing Window: ~{analysis_summary['Premium_Pricing_Window_Years']:.0f} years (2028-2032)
• First Generic Threat: Semaglutide generics in January 2032
• Second Generic Threat: Tirzepatide generics in July 2039
• VK2735 Patent Life: ~{analysis_summary['VK2735_Patent_Protection_Years']:.0f} years from launch

OUTPUTS CREATED:
────────────────
• data/patent_landscape.csv - Patent expiry data for key drugs
• results/patent_cliff_analysis.md - Full strategic analysis

STRATEGIC IMPLICATION:
──────────────────────
Viking has a 4-year window of premium pricing before the first
generic competitor (Semaglutide) enters the US market, providing
sufficient runway to establish market presence and generate ROI.
""")
