"""Redraw selected historical report results and clearly labeled scenarios.

Sources: Qualcomm team report (16 Nov 2023), pp. 6–11; Kelun Wang & Team,
Growth Strategy for Pagoda (2021 Bain Cup), slides 4, 13–17.
Original files stay outside the public website. No source model is claimed.
"""
from pathlib import Path
from html import escape
import json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
ROOT=Path(__file__).resolve().parents[2]
Q=ROOT/'projects/qualcomm-valuation/assets';B=ROOT/'projects/bain-cup-pagoda/assets'
Q.mkdir(parents=True,exist_ok=True);B.mkdir(parents=True,exist_ok=True)
plt.rcParams.update({'font.family':'DejaVu Sans','svg.fonttype':'none','font.size':10,'axes.spines.top':False,'axes.spines.right':False})
qdata={'units':'USD billions; reported study values, not a revised valuation',
 'operating_income':7.788,'lease_adjustment':.0397594,'rd_adjustment':2.6745714,
 'tax_rate_assumption':.21,'after_tax_adjusted_operating_income':8.2968414,
 'reinvestment':1.8205714,'fcff':6.47627,
 'pv_explicit_flows':[6.9983247,7.5624626,8.1720758,8.8308301,9.5426870],
 'pv_terminal':148.8981828,'reported_operating_value':190.0045629,
 'cash':8.45,'report_debt_input':29.663,'reported_equity_value':168.7915629,
 'shares_billions':1.114,'reported_value_per_share':151.5184586,
 'stable_wacc_assumption':.0865,'stable_growth_assumption':.0533}
assert abs((qdata['operating_income']+qdata['lease_adjustment']+qdata['rd_adjustment'])*.79-qdata['reinvestment']-qdata['fcff'])<1e-6
assert abs(sum(qdata['pv_explicit_flows'])+qdata['pv_terminal']-qdata['reported_operating_value'])<1e-6
assert abs(qdata['reported_operating_value']+8.45-29.663-qdata['reported_equity_value'])<1e-6
(Q/'results.json').write_text(json.dumps(qdata,indent=2)+'\n')
bdata={'source':'Kelun Wang & Team, 2021 Bain Cup, slide 4',
 'units':'RMB billions; approximate values transcribed from the slide',
 'years':['2015','2018','2019','2020','2021E','2023E'],
 'market':[750,950,1050,1000,1150,1500],
 'fruit_lab_cities':['Shanghai','Beijing','Shenzhen','Guangzhou','Nanjing','Hangzhou','Wuhan'],
 'city_exclusive_cities':['Changsha','Sanya','Chongqing'],
 'planned_fruit_labs_before_2024':10,'planned_city_exclusive_stores_before_2024':8}
(B/'results.json').write_text(json.dumps(bdata,indent=2)+'\n')
for mode in ['light','dark']:
 bg,ink,muted,line=('#f8f6ef','#27342f','#69766f','#d9ded5') if mode=='light' else ('#202825','#e2e9e3','#afbeb4','#415249')
 green,blue,coral=('#91b5a2','#9fb7d0','#d4a394') if mode=='light' else ('#6eaa8b','#7e9fca','#c59280')
 def setup(title,sub,size=(10,5.8)):
  fig,ax=plt.subplots(figsize=size);fig.patch.set_facecolor(bg);ax.set_facecolor(bg)
  ax.tick_params(colors=muted);ax.spines[['left','bottom']].set_color(line);ax.grid(axis='y',color=line,alpha=.55);ax.set_axisbelow(True)
  fig.text(.07,.94,title,color=ink,fontsize=17,weight='medium');fig.text(.07,.885,sub,color=muted,fontsize=10)
  fig.subplots_adjust(left=.1,right=.96,bottom=.19,top=.79);return fig,ax
 def save(fig,dest,name):
  fig.savefig(dest/f'{name}-{mode}.svg',facecolor=bg);plt.close(fig)
 fig,ax=setup('From operating income to free cash flow','Reconstructed adjustment bridge • historical study • USD billions')
 labels=['Operating\nincome','Lease\nadjustment','R&D\nadjustment','Tax on\nadjusted EBIT','Reinvestment','FCFF']
 vals=[7.788,.0397594,2.6745714,-2.205489468,-1.8205714,6.47627]; running=0
 for i,v in enumerate(vals):
  if i==5:bottom=0;color=blue
  else:bottom=running if v>=0 else running+v;color=green if v>0 else coral
  ax.bar(i,abs(v),bottom=bottom,color=color,width=.67,zorder=3)
  top=bottom+abs(v);ax.text(i,top+.18,f'{v:+.3f}' if i in [1,2,3,4] else f'{v:.3f}',ha='center',color=ink,fontsize=10)
  if i<5:
   running+=v
   if i<4:ax.plot([i+.34,i+.66],[running,running],color=muted,lw=.8)
 ax.set_xticks(range(6),labels,color=ink);ax.set_ylim(0,12);ax.set_ylabel('USD bn',color=muted);save(fig,Q,'cash-flow-bridge')
 fig,ax=setup('Most operating value sits beyond the explicit forecast','Reported valuation bridge • USD billions • original assumptions retained')
 names=['2024–2028\nPV of FCFF','PV of\nterminal value','Operating\nvalue','Cash','Report debt\ninput','Equity\nvalue']; vals=[sum(qdata['pv_explicit_flows']),148.8981828,190.0045629,8.45,-29.663,168.7915629]
 bottoms=[0,vals[0],0,vals[2],vals[2]+8.45-29.663,0]
 for i,(v,b) in enumerate(zip(vals,bottoms)):
  ax.bar(i,abs(v),bottom=b,width=.65,color=coral if i==4 else blue if i in [2,5] else green,zorder=3)
  ax.text(i,b+abs(v)+5,f'{v:,.2f}',ha='center',color=ink,fontsize=10)
 ax.set_xticks(range(6),names,color=ink);ax.set_ylim(0,231);ax.set_ylabel('USD bn',color=muted)
 fig.text(.1,.07,'Terminal value = 78.4% of reported operating value. Debt input requires reconciliation.',color=muted,fontsize=10);save(fig,Q,'valuation-bridge')
 # Keep next-year NOPAT fixed, vary growth and return on new capital together.
 growth=np.array([.02,.03,.04,.0533]);roc=np.array([.07,.0865,.10,.12]);wacc=.0865
 values=(1-growth[None,:]/roc[:,None])/(wacc-growth[None,:])
 fig,ax=setup('Growth creates value when returns exceed the cost of capital','New sensitivity illustration • terminal value / next-year NOPAT • WACC 8.65%')
 cmap=LinearSegmentedColormap.from_list('site',[bg,green]);ax.grid(False);ax.imshow(values,cmap=cmap,aspect='auto',vmin=0,vmax=20)
 for i in range(4):
  for j in range(4):ax.text(j,i,f'{values[i,j]:.2f}×',ha='center',va='center',fontsize=15,color=ink)
 ax.set_xticks(range(4),['2%','3%','4%','5.33%']);ax.set_yticks(range(4),['7%','8.65%','10%','12%']);ax.set_xlabel('Stable growth assumption',color=muted);ax.set_ylabel('Return on new capital',color=muted)
 ax.spines[['left','bottom']].set_visible(False);save(fig,Q,'growth-sensitivity')
 fig,ax=setup('The opportunity was a growing market with changing channels','2021 presentation estimates • China fresh fruit retail • approximate RMB billions')
 xs=np.arange(6);ax.bar(xs,bdata['market'],color=[green]*4+[blue]*2,width=.65)
 for i,v in enumerate(bdata['market']):ax.text(i,v+45,f'~{v:,}',ha='center',color=ink)
 ax.axvspan(3.5,5.5,facecolor=blue,alpha=.12);ax.set_xticks(xs,bdata['years'],color=ink);ax.set_ylim(0,1800);ax.set_ylabel('RMB bn',color=muted)
 fig.text(.1,.07,'E = forecast in the 2021 deck. These are not verified realized 2021 or 2023 results.',fontsize=10,color=muted);save(fig,B,'market-context')
 # Source-grounded store-format comparison, rendered as vectors.
 parts=[f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 640"><title>Two store concepts with different customer occasions</title><rect width="1000" height="640" fill="{bg}"/>']
 def text(x,y,t,size=17,col=ink):parts.append(f'<text x="{x}" y="{y}" font-family="sans-serif" font-size="{size}" fill="{col}">{escape(t)}</text>')
 text(38,48,'Two store formats, two reasons to visit',27);text(38,80,'Redrawn from the 2021 proposal by Kelun Wang & Team • not implemented-store results',15,muted)
 for x,title,lines,color in [(38,'Fruit Lab',['Occasion / everyday exploration','DIY juice, workshops, premium fruit','Location / CBDs and urban complexes','7 priority cities','Shanghai · Beijing · Shenzhen','Guangzhou · Nanjing · Hangzhou · Wuhan','Original expansion proposal','~10 labs before 2024'],green),(514,'City Exclusive Store',['Occasion / travel and gifting','Local fruit, city themes, gift packaging','Location / landmarks and tourism hubs','3 priority cities','Changsha · Sanya · Chongqing','','Original expansion proposal','~8 stores before 2024'],coral)]:
  parts.append(f'<rect x="{x}" y="118" width="448" height="474" rx="14" fill="none" stroke="{line}" stroke-width="2"/><rect x="{x}" y="118" width="448" height="8" rx="4" fill="{color}"/>')
  text(x+22,170,title,26)
  for j,s in enumerate(lines):text(x+22,219+j*44,s,15 if j in [4,5] else 17,muted if j in [0,2,6] else ink)
 parts.append('</svg>');(B/f'store-formats-{mode}.svg').write_text(''.join(parts))
print('Generated 10 themed SVGs and two aggregate source-data files.')
