import json

# Load data
with open('data/crm_financials.json', 'r') as f:
    data = json.load(f)

# Extract key data
fcf_history = [(cf['fiscal_year'], cf['free_cash_flow']) for cf in data['cash_flow_statements_annual']]
latest_fcf = fcf_history[-1][1]  # 2025 FCF
metrics = data['financial_metrics_snapshot']
balance = data['latest_balance_sheet']
price = data['price_snapshot']['price']
shares = balance['outstanding_shares']

# Step 1: Calculate FCF Growth Rate
fcf_2021 = fcf_history[0][1]
fcf_2025 = fcf_history[-1][1]
cagr = (fcf_2025 / fcf_2021) ** (1/4) - 1

print("="*70)
print("SALESFORCE (CRM) DCF VALUATION ANALYSIS")
print(f"As of: {data['as_of_date']}")
print(f"Current Price: ${price:.2f}")
print("="*70)

print("\n1. FCF GROWTH ANALYSIS")
print("-" * 70)
for year, fcf in fcf_history:
    print(f"  FY{year}: ${fcf/1e9:.2f}B")
print(f"\n  5-Year CAGR: {cagr*100:.1f}%")
print(f"  Recent YoY Growth: {metrics['free_cash_flow_growth']*100:.1f}%")
print(f"  Revenue Growth: {metrics['revenue_growth']*100:.1f}%")

# Use conservative growth rate (cap at 15%, apply haircut)
base_growth = 0.12  # Between 14% FCF growth and analyst estimates
print(f"\n  → Selected Base Growth Rate: {base_growth*100:.0f}% (conservative)")

# Step 2: Calculate WACC
print("\n2. WACC CALCULATION")
print("-" * 70)
print(f"  Sector: {data['company_facts']['sector']}")
print(f"  Base WACC Range: 8.0% - 9.5% (midpoint: 8.75%)")
print(f"\n  Adjustments:")
print(f"    Debt/Equity = {metrics['debt_to_equity']:.2f} (< 0.30) → -0.30%")
print(f"    Market Cap = ${metrics['market_cap']/1e9:.1f}B (> $100B) → -0.20%")
print(f"    ROIC = {metrics['return_on_invested_capital']*100:.0f}% (> 15%) → -0.20%")

wacc = 0.08  # 8.75% - 0.70% = 8.05%, rounded to 8.0%
print(f"\n  → Final WACC: {wacc*100:.1f}%")
print(f"  → ROIC-WACC Spread: {(metrics['return_on_invested_capital']-wacc)*100:.1f}% ✓")

# Step 3: Project Cash Flows
print("\n3. PROJECTED FREE CASH FLOWS")
print("-" * 70)
terminal_growth = 0.025

fcf_projections = []
current_fcf = latest_fcf

for year in range(1, 6):
    decay_factor = 1 - (year - 1) * 0.05  # 100%, 95%, 90%, 85%, 80%
    growth_rate = base_growth * decay_factor
    current_fcf = current_fcf * (1 + growth_rate)
    pv = current_fcf / ((1 + wacc) ** year)
    fcf_projections.append({
        'year': 2025 + year,
        'fcf': current_fcf,
        'growth': growth_rate,
        'pv': pv
    })
    print(f"  {2025+year}: ${current_fcf/1e9:.2f}B (growth: {growth_rate*100:.1f}%) → PV: ${pv/1e9:.2f}B")

# Terminal Value
terminal_fcf = fcf_projections[-1]['fcf'] * (1 + terminal_growth)
terminal_value = terminal_fcf / (wacc - terminal_growth)
terminal_pv = terminal_value / ((1 + wacc) ** 5)

print(f"\n  Terminal Value (g={terminal_growth*100:.1f}%): ${terminal_value/1e9:.2f}B → PV: ${terminal_pv/1e9:.2f}B")

# Step 4: Calculate Fair Value
pv_sum = sum(p['pv'] for p in fcf_projections)
enterprise_value = pv_sum + terminal_pv

net_debt = balance['total_debt'] - balance['cash_and_equivalents'] - balance['current_investments']
equity_value = enterprise_value - net_debt
fair_value_per_share = equity_value / shares

print("\n4. VALUATION SUMMARY")
print("-" * 70)
print(f"  PV of 5-Year FCF: ${pv_sum/1e9:.2f}B")
print(f"  PV of Terminal Value: ${terminal_pv/1e9:.2f}B")
print(f"  Enterprise Value: ${enterprise_value/1e9:.2f}B")
print(f"  Less: Net Debt: ${net_debt/1e9:.2f}B")
print(f"  Equity Value: ${equity_value/1e9:.2f}B")
print(f"  Shares Outstanding: {shares/1e6:.0f}M")
print(f"\n  → Fair Value per Share: ${fair_value_per_share:.2f}")
print(f"  → Current Price: ${price:.2f}")
upside = (fair_value_per_share - price) / price * 100
print(f"  → Implied Upside: {upside:+.1f}%")

# Step 5: Sanity Checks
print("\n5. SANITY CHECKS")
print("-" * 70)
reported_ev = metrics['enterprise_value']
ev_diff = abs(enterprise_value - reported_ev) / reported_ev * 100
print(f"  ✓ EV Check: Calculated ${enterprise_value/1e9:.1f}B vs Reported ${reported_ev/1e9:.1f}B ({ev_diff:.1f}% diff)")

tv_ratio = terminal_pv / enterprise_value * 100
print(f"  ✓ Terminal Value: {tv_ratio:.1f}% of total EV (target: 50-80%)")

fcf_per_share = metrics['free_cash_flow_per_share']
fcf_multiple_low = fcf_per_share * 15
fcf_multiple_high = fcf_per_share * 25
print(f"  ✓ FCF Multiple Check: ${fcf_multiple_low:.0f} - ${fcf_multiple_high:.0f} (Fair value: ${fair_value_per_share:.2f})")

# Step 6: Sensitivity Analysis
print("\n6. SENSITIVITY ANALYSIS (Fair Value per Share)")
print("-" * 70)

def calc_fair_value(wacc_input, term_growth):
    fcf = latest_fcf
    pv_total = 0
    for year in range(1, 6):
        decay = 1 - (year - 1) * 0.05
        fcf = fcf * (1 + base_growth * decay)
        pv_total += fcf / ((1 + wacc_input) ** year)
    
    tv = fcf * (1 + term_growth) / (wacc_input - term_growth)
    tv_pv = tv / ((1 + wacc_input) ** 5)
    ev = pv_total + tv_pv
    eq = ev - net_debt
    return eq / shares

wacc_range = [0.07, 0.08, 0.09]
growth_range = [0.020, 0.025, 0.030]

print("\n           Terminal Growth Rate")
print("  WACC  |   2.0%  |   2.5%  |   3.0%")
print("  ------|---------|---------|--------")
for w in wacc_range:
    row = f"  {w*100:.1f}% |"
    for g in growth_range:
        fv = calc_fair_value(w, g)
        row += f" ${fv:6.2f} |"
    print(row)

print("\n" + "="*70)
print("RECOMMENDATION")
print("="*70)
if upside > 15:
    rec = "UNDERVALUED - Consider accumulation"
elif upside < -15:
    rec = "OVERVALUED - Consider trimming"
else:
    rec = "FAIRLY VALUED - Hold position"
print(f"  {rec}")
print(f"\n  Base case suggests {upside:+.1f}% upside from current levels.")
print(f"  Sensitivity range: ${calc_fair_value(0.09, 0.02):.2f} - ${calc_fair_value(0.07, 0.03):.2f}")
print("="*70)

