"""Ward County case: reproduce illustrative debt sizing and the delivery-time decision.

Python 3; no dependencies. All model amounts are USD millions.
The signed agreement applies its actual model by tranche and payment date.
"""
from pathlib import Path
from xml.sax.saxutils import escape
import json

HERE = Path(__file__).resolve().parent
WARD = 'https://www.sec.gov/Archives/edgar/data/2110365/000119312526395475/ck0002110365-ex10_23.htm'
NC = 'https://www.sec.gov/Archives/edgar/data/2110365/000119312526395475/ck0002110365-ex10_24.htm'
S1 = 'https://www.sec.gov/Archives/edgar/data/2110365/000119312526458722/ck0002110365-20261112.htm'
NVDA = 'https://www.sec.gov/Archives/edgar/data/1045810/000104581026000088/q3fy27cfocommentary.htm'

def sizing(cost=1000, cash=260, rate=.06375, years=5, limit=.9, cover=1.3):
    if min(cost,cash,rate)<0 or years<1 or not 0<=limit<=1 or cover<=0:
        raise ValueError('Invalid scenario')
    pv = sum((1+rate)**(-year) for year in range(1,years+1))
    d_cost, d_cash = cost*limit, cash/cover*pv
    lending = min(d_cost,d_cash)
    return dict(cost=cost,annual_post_opex_contracted_cash=cash,annual_rate=rate,years=years,
                cost_cap=d_cost,coverage_cap=d_cash,eligible_debt_if_other_conditions_met=lending,
                residual_sponsor_capital=cost-lending,annual_cash_needed_to_use_cost_cap=d_cost/pv*cover,
                binding_test='coverage' if d_cash<d_cost else 'cost')

cases = dict(base=sizing(),minus_50_bps=sizing(rate=.05875),plus_10_annual_cash=sizing(cash=270),
             plus_25_annual_cash=sizing(cash=285))
base=cases['base']['eligible_debt_if_other_conditions_met']
assert round(base,3)==833.947
assert round(cases['minus_50_bps']['eligible_debt_if_other_conditions_met']-base,3)==11.398
assert round(cases['plus_10_annual_cash']['eligible_debt_if_other_conditions_met']-base,3)==32.075
assert cases['plus_25_annual_cash']['eligible_debt_if_other_conditions_met']==900
assert sizing(cash=0)['eligible_debt_if_other_conditions_met']==0
assert sizing(rate=0)['binding_test']=='cost'

data={
    'as_of':'2026-11-24', 'units':'USD millions except dates, ratios and rates',
    'sources':{'ward_execution':WARD,'north_carolina_execution':NC,'nscale_nov_12':S1,'nvidia_q3_commentary':NVDA},
    'observed':{
        'ward':{'signed':'2026-08-27','commitment':1850,'fixed_delayed_draw':630,'floating_delayed_draw':1220,
                'term_sofr_margin_bps':237.5,'outer_maturity':'2033-02-27','ratings_disclosed':'investment-grade, stable',
                'advance_cost_ratio':.90,'minimum_sizing_dscr':1.30,
                'primary_delivery_days_before_customer_delivery':45,'level_3_testing_days_before_customer_delivery':60,
                'locator':'Article I: Tranche Advance Rate, Sizing DSCR; §§2.08, 4.02(a), (d)–(k); consult qualifications in filing',
                'actual_draw_for_hypothetical_tranche':None},
        'north_carolina':{'signed':'2026-08-27','commitment':1200,'fixed_delayed_draw':370,'floating_delayed_draw':830,
                          'term_sofr_margin_bps':237.5,'outer_maturity':'2031-12-27','ratings_disclosed':'investment-grade, stable'},
        'monarch':{'disclosure_date':'2026-11-12','binding_qualifying_funding_disclosed_as_of_that_filing':False,
                   'perimeter':'Different project; not a use of these two facilities.'},
        'nvidia':{'latest_quarter_commentary_as_of_check':'2026-11-17','q3_10q_identified_as_of_check':False}},
    'hypothetical': {
       'basis':'One $1bn equipment tranche; five equal annual debt-service payments; constant annual cash after stated operating costs. 4% assumed SOFR plus 237.5 bp. Contract uses tranche/payment-date sizing. No reserves, fees, actual amortization, capex outside equipment or hedge cash flows. Sufficient facility commitment assumed.',
       'size_cases':cases,
       'timing_cases':{'eligible_at_equipment_payment':{'bank_cash':base,'sponsor_cash':1000-base},
                       'missed_deadline_and_no_usable_customer_prepayment':{'bank_cash_at_equipment_payment':0,'sponsor_cash':1000,
                       'extra_sponsor_cash_at_equipment_payment':base,'post_acceptance_possible_reimbursement':base,
                       'basis':'Equipment/title, technical and other lender conditions otherwise met; assume funding only after qualifying acceptance in late case, same sizing then. No waiver. Model is not a funding claim.'}}}}

def figure(zh,mobile):
    w,h=(460,747) if mobile else (940,685)
    m=20 if mobile else 30
    ink,teal,grey,gold,pale='#142F41','#08786B','#415C6A','#A05524','#EFEDE2'
    a=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="{h}" viewBox="0 0 {w} {h}" role="img" aria-labelledby="t d">']
    tr=lambda en,cn:cn if zh else en
    def rec(x,y,ww,hh,c):a.append(f'<rect x="{x}" y="{y}" width="{ww}" height="{hh}" fill="{c}"/>')
    def tx(x,y,s,n=14,c=ink,b=False):a.append(f'<text x="{x}" y="{y}" font-family="Arial, Microsoft YaHei, sans-serif" font-size="{n}" font-weight="{700 if b else 400}" fill="{c}">{escape(str(s))}</text>')
    title=tr('When the GPU loan pays','GPU 贷款，到底什么时候放款？')
    a.extend([f'<title id="t">{title}</title>','<desc id="d">Ward County agreement: the lower of 90 percent of eligible cost and debt allowed by a 1.30 times coverage test. A timing miss moves the first equipment check to sponsor cash in the example.</desc>'])
    rec(0,0,w,h,'#F7F5EF');rec(0,0,w,6,teal)
    tx(m,34,'AI INFRA CREDIT  /  24 NOV 2026',12,teal,True);tx(m,72,title,25 if mobile else 35,ink,True)
    tx(m,103,tr('Nscale Ward County | $1.85bn signed commitment','Nscale 得州 Ward County｜签约额度 18.5 亿美元'),14,grey)
    tx(m,139,tr('01  The lesser of two limits','01  两道门槛，取较低金额'),16 if mobile else 19,ink,True)
    ww=(w-2*m-8)//2
    for i,(v,l) in enumerate([('90%',tr('of eligible GPU capex','合格 GPU 资本开支')),('1.30x',tr('coverage on each payment date','各付款日的偿债覆盖倍数'))]):
        x=m+i*(ww+8);rec(x,154,ww,60,'#E0EEE8');tx(x+8,183,v,25,teal,True);tx(x+8,203,l,12,grey)
    tx(m,249,tr('02  What changes loan size?','02  什么能让银行多放款？'),16 if mobile else 19,ink,True)
    tx(m,273,tr('Illustrative $1bn tranche. USD millions.','假设一批设备成本 10 亿美元。图中单位：百万美元。'),12,grey)
    for i,(label,value) in enumerate([
      (tr('Baseline','基准'),base),
      (tr('Rate 50 bp lower','利率降低 50 基点'),cases['minus_50_bps']['eligible_debt_if_other_conditions_met']),
      (tr('Annual cash +$10m','每年合同净现金多 1,000 万'),cases['plus_10_annual_cash']['eligible_debt_if_other_conditions_met']),
      (tr('Annual cash +$25m','每年合同净现金多 2,500 万'),900)]):
        y=291+i*34;rec(m,y,w-2*m,30,'#F0EDE3' if i==3 else '#E9EFEB')
        tx(m+8,y+20,label,12 if mobile else 15);tx(w-m-67,y+20,f'{value:.0f}',16,teal,True)
    tx(m,448,tr('03  Who pays for the same GPUs first?','03  同一批 GPU，谁先付钱？'),16 if mobile else 19,ink,True)
    tx(m,473,tr('Illustrative funding at the equipment payment date','假设情景：在设备付款当天比较资金来源'),12,grey)
    for i,(k,title,b,s) in enumerate([
       ('A',tr('Milestones met','按期满足节点'),834,166),('B',tr('Late; waiting for acceptance','延期，等客户验收'),0,1000)]):
        y=490+i*(88 if mobile else 71);tx(m,y+15,k+'  '+title,13,ink,True)
        bw=w-2*m
        if b:rec(m,y+25,bw*b/1000,18,teal)
        rec(m+bw*b/1000,y+25,bw*s/1000,18,gold)
        tx(m,y+61,tr(f'Bank {b:,}  |  Sponsor {s:,}',f'银行 {b:,}  |  股东 {s:,}'),12,grey)
    y=676 if mobile else 641
    tx(m,y,tr('No usable customer advance, no waiver; later takeout conditional.','假定无可用客户预付款、无豁免；后续置换仍需满足条件。'),11,grey)
    tx(m,y+18,tr('Source: Ward County credit agreement, §4.02 and Article I.','来源：Ward County 贷款协议第 4.02 节及第一章。'),11,grey)
    a.append('</svg>')
    return '\n'.join(a)

if __name__=='__main__':
    (HERE/'ward-model.json').write_text(json.dumps(data,indent=2)+'\n',encoding='utf-8')
    for zh in (False,True):
        for mobile in (False,True):
            name='ward-credit'+('-zh' if zh else '')+('-mobile' if mobile else '')+'.svg'
            (HERE/name).write_text(figure(zh,mobile),encoding='utf-8')
