import json
from datetime import datetime

with open('/tmp/case3_analysis_2026-11-07.json', 'r') as f:
    data = json.load(f)

# === 更新 BB Alert 分析 ===
for alert in data['alerts']:
    idx = alert['index']
    
    # Mercedes-Benz (alerts 3-7)
    if idx in [3, 4, 5, 6, 7]:
        alert['analysis'] = (
            "【S&P 降評已確認】2026-11-05 S&P 將 Mercedes-Benz Group AG 長期發行人評級由 A 降至 A-，"
            "短期評級由 A-1 降至 A-2，展望 Negative。Moody's 維持 A2/Stable 未動。"
            "降評原因：中國豪華車市場疲弱、EV 轉型成本、持續高 R&D 支出，2027-28 年調整後 EBITDA 利潤率預計仍低於 10%。"
            "Cars 部門 2026 年 RoS 指引下調至 2-3%（前值 3-5%）。"
            "Scope 亦將集團評級由 A+ 降至 A，底層業務風險評估由 BBB+ 降至 BBB。"
            "供應鏈金融影響：貿易應付款 Q3 2026 升至 €14.9B（年初 €10.7B），MBIF 應收款分類仍在 IFRS9 Stage 1，無顯著信用惡化。"
            "Siegfried 暴露：SCF USD 13.4M + SCP6-2 USD 11.4M = USD 24.8M。"
            "距 BBB+/Baa1 門檻：S&P A- 高 2 個 notch；Moody's A2 高 3 個 notch，仍屬穩健投資級。"
            "短期無降至 Sub-IG 風險，但 Negative 展望意味若業績未改善 S&P 可能再降一次至 BBB+。"
        )
        alert['risk_level'] = "MEDIUM"
        alert['scf_impact'] = "負面但可控。A- 仍遠高於 BBB+，SCF 應收款無顯著惡化跡象。若再降至 BBB+ 仍合規，需持續監控展望。"
        alert['recommended_action'] = "MONITOR"
        alert['verification_level'] = "HIGH - S&P 官方確認，5 筆 Alert 交叉驗證"

    # Unilever Myanmar (alerts 8, 16)
    elif idx in [8, 16]:
        alert['analysis'] = (
            "【Unilever 緬甸 JV 出售】Unilever PLC 同意將緬甸合資公司 UEMCL 全部股權出售予 Centig Holding"
            "（EAC 長期合作夥伴附屬公司），交易金額未披露，預計 2027 年完成。"
            "對 Unilever PLC（Siegfried 交易對手）信用無實質影響：緬甸業務佔集團營收比例極低，屬主動撤出新興市場操作。"
            "Siegfried 暴露針對 Unilever PLC 本身（SCP2 USD 4.6M + SCP5 USD 2.5M + SCP6-2 USD 15.4M = USD 22.5M）。"
            "交易方向：Unilever 為賣方（SELL）；Alert 8 顯示 AMBIGUOUS 係因原始訊息包含買賣雙方資訊。"
        )
        alert['risk_level'] = "LOW"
        alert['scf_impact'] = "無影響。緬甸業務非重要資產，Unilever PLC 信用評級不受此次出售影響。"
        alert['recommended_action'] = "MONITOR"
        alert['verification_level'] = "HIGH - 多方媒體交叉確認（CNA / DVB / MarketScreener）"

    # Alfa Laval (alert 13)
    elif idx == 13:
        alert['analysis'] = (
            "【Alfa Laval 收購 Navtor AS】2026-11-06 宣布以 USD 700M（SEK 68.5億）全現金收購挪威海事軟件商 Navtor AS，"
            "預計 Q1 2027 完成（待監管批准）。Navtor 加入 Alfa Laval 海洋部門。"
            "信用評估：收購以自有現金及既有融資計劃支應，S&P 無降評動作。"
            "短期利潤率影響中性，長期戰略協同正面。USD 700M 相對 Alfa Laval 體量屬可控規模。"
            "Siegfried 暴露：SCP5 USD 20M + SCP6-2 USD 5M = USD 25M，信用質素無實質變化。"
        )
        alert['risk_level'] = "LOW"
        alert['scf_impact'] = "無顯著影響。Alfa Laval 仍屬穩健投資級，收購屬正常業務擴張。"
        alert['recommended_action'] = "MONITOR"
        alert['verification_level'] = "HIGH - Alfa Laval 官方新聞稿確認"

    # Epiroc (alerts 9, 14)
    elif idx in [9, 14]:
        alert['analysis'] = (
            "【Epiroc 收購 Aramine SAS】收購法國礦山備件供應商 Aramine SAS（年收入 €31M），交易金額未披露，"
            "預計 Q4 2026 完成。信用影響：S&P 確認 Epiroc BBB+/Stable，"
            "FFO/debt 預計維持 80-85%，S&P 明確表示 Epiroc 財務靈活性足以支持此類小型收購而不影響 BBB+ 評級。"
            "交易規模微小，評級影響可忽略，甚至略為正面（提升售後服務收入）。"
            "Siegfried 暴露：SCP5 USD 9.6M + SCP6-2 USD 18.9M = USD 28.5M，信用質素穩定。"
        )
        alert['risk_level'] = "LOW"
        alert['scf_impact'] = "無影響。S&P 明確確認此類收購不影響 BBB+ 評級，財務指標穩健。"
        alert['recommended_action'] = "MONITOR"
        alert['verification_level'] = "HIGH - S&P 評級文件及 Epiroc 官方公告確認"

    # Johnson Controls (alert 17)
    elif idx == 17:
        alert['analysis'] = (
            "【Johnson Controls 預設風險 IG1→IG2】此 Alert 為彭博終端內部風險分類變動（非評級機構行動）。"
            "實際評級：S&P BBB+/A-2/Stable（截至 2026-06-30），Moody's Baa1/P-2/Stable。"
            "兩家機構均維持穩定展望，無降評信號。IG2 歸類反映模型內部信用質素微降，仍屬穩健投資級上段。"
            "公司持有 USD 2.5B 循環信貸，流動性充裕。"
            "Siegfried 暴露：SCP4 USD 5.4M，風險可控。"
        )
        alert['risk_level'] = "LOW"
        alert['scf_impact'] = "輕微關注。IG1→IG2 係彭博內部分類，非實際評級行動。BBB+/Baa1/Stable 信用質素未變。"
        alert['recommended_action'] = "MONITOR"
        alert['verification_level'] = "HIGH - S&P 及 Moody's 官方評級確認"

    # KMB (alert 1) - no Siegfried position
    elif idx == 1:
        alert['analysis'] = (
            "Kimberly-Clark 旗下 Dilek Gida 收購女性衛生業務。Siegfried 無持倉，無需進一步分析。"
        )
        alert['risk_level'] = "N/A"
        alert['scf_impact'] = "無影響（Siegfried 無持倉）"
        alert['recommended_action'] = "N/A"
        alert['verification_level'] = "LOW - 無持倉，不執行深度查核"

    # CRRFY (alert 2) - no Siegfried position
    elif idx == 2:
        alert['analysis'] = "Carrefour 子公司相關收購。Siegfried 無持倉，無需進一步分析。"
        alert['risk_level'] = "N/A"
        alert['scf_impact'] = "無影響（Siegfried 無持倉）"
        alert['recommended_action'] = "N/A"
        alert['verification_level'] = "LOW"

    # EDF (alert 10) - no Siegfried position
    elif idx == 10:
        alert['analysis'] = "EDF Fitch 展望降至 Negative。Siegfried 無持倉，無需進一步分析。"
        alert['risk_level'] = "N/A"
        alert['scf_impact'] = "無影響（Siegfried 無持倉）"
        alert['recommended_action'] = "N/A"
        alert['verification_level'] = "LOW"

    # ENEL (alert 11), ITOCHU (alert 12), NVDA (alert 15), Hyundai (alert 18)
    elif idx in [11, 12, 15, 18]:
        alert['analysis'] = "Siegfried 無持倉，無需進一步分析。"
        alert['risk_level'] = "N/A"
        alert['scf_impact'] = "無影響（Siegfried 無持倉）"
        alert['recommended_action'] = "N/A"
        alert['verification_level'] = "LOW"

# === 更新 WhiteList 深度分析 ===
wl_analysis = {
    "run_at": datetime.now().isoformat(),
    "high_severity": [
        {
            "company": "Thyssenkrupp AG",
            "current_ratings": {"SP": "BB/B", "Moodys": "Ba3/NP", "outlooks": "Stable/Stable"},
            "distance_from_threshold": "S&P: 4 notches below BBB+ | Moody's: 4 notches below Baa1 — SUB-INVESTMENT GRADE",
            "downgrade_risk": "目前展望穩定，無即時降評風險。但已長期處於次投資級。",
            "fcf_status": "FY2026 FCF before M&A 指引負 €300–600M，前 9 個月 FCF -€1.94B。可用流動性 €5.3B，淨金融資產 €2.6B。tk accelis 已於 2026-10-28 分拆上市。",
            "siegfried_exposure": "無基金敞口",
            "web_search_findings": "Thyssenkrupp 2026 年仍為 Sub-IG（BB/Ba3），WhiteList 資格根本不符合投資級標準。",
            "recommended_action": "INVESTIGATE",
            "action_detail": "Thyssenkrupp 現評級 BB/Ba3 屬次投資級，與 Siegfried BBB+/Baa1 門檻差距 4 個 notch。雖無現有敞口，但 WhiteList 配置資格需立即重新審視。若未來有交易需求，必須先提請 Derek 批准豁免，或從 WhiteList 移除。",
            "monitoring_frequency": "每月（監控 FCF 改善及評級升降信號）"
        },
        {
            "company": "LG Chem Ltd.",
            "current_ratings": {"SP": "BBB/Negative", "Moodys": "Baa2/Stable", "Korea": "AA（KIS）/ AA+負面（KR）"},
            "distance_from_threshold": "S&P: 1 notch below BBB+ | Moody's: 1 notch below Baa1 — 低於 Siegfried 投資門檻",
            "downgrade_risk": "S&P 下調觸發線：debt/EBITDA > 3.5x 持續。預計 2026 年全年仍超過門檻，2027 年才望降至 3.1x。",
            "fcf_status": "Q1 2026 淨虧 KRW 78.2B；石化 EV 電池雙重承壓；短期債務 KRW 13.1T，總債務 KRW 35.7T。",
            "siegfried_exposure": "無基金敞口",
            "web_search_findings": "S&P 2026-03 確認 BBB/Negative；Moody's 2025-11 由 Baa1 降至 Baa2；韓國評級機構亦調負面展望。Oct 2026 Moody's 完成定期審查，未披露新行動。",
            "recommended_action": "INVESTIGATE",
            "action_detail": "LG Chem 目前評級 BBB/Baa2，均低於 Siegfried BBB+/Baa1 門檻。若 Siegfried 最低要求為 BBB+/Baa1，LG Chem 現在已不符合標準。S&P Negative 展望下若再降至 BBB-，仍為投資級，但距離垃圾級僅一步之遙。需 Derek 確認 LG Chem 在 WhiteList 的批准基礎。",
            "monitoring_frequency": "每週（密切追蹤 S&P Negative 展望是否觸發降評）"
        },
        {
            "company": "Rogers Communications Inc.",
            "current_ratings": {"SP": "BBB-/Negative", "Moodys": "Baa3/Stable", "DBRS": "BBB(Low)"},
            "distance_from_threshold": "S&P: 2 notches below BBB+ | Moody's: 2 notches below Baa1 — 明顯低於門檻",
            "downgrade_risk": "高。S&P 下調觸發線：year-end 2026 leverage 4.0x。現預計達 4.6x。若 MLSE 貨幣化延誤或不足，2027H2 前降評風險實質存在。若降至 BB+/Ba1，Siegfried 須強制退出任何持倉。",
            "fcf_status": "MLSE 收購融資 C$4.35B，總長期債務 C$37.47B。計劃削減 2026 Capex C$800M 以支持去槓桿。",
            "siegfried_exposure": "無基金敞口",
            "web_search_findings": "S&P 確認 BBB-/Negative；leverage 4.6x > 下調觸發 4.0x；下調風險「實質而非即時」。MLSE 貨幣化是去槓桿關鍵。",
            "recommended_action": "MONITOR",
            "action_detail": "Rogers 目前評級 BBB-/Baa3，低於 BBB+/Baa1 門檻 2 個 notch。現無 Siegfried 敞口，降評風險確實存在。建議每週監控，若 S&P 開始負面觀察（CreditWatch Negative），立即通報 Derek。",
            "monitoring_frequency": "每週（監控 MLSE 貨幣化進展及 S&P 展望更新）"
        },
        {
            "company": "Pirelli & C. S.p.A.",
            "current_ratings": {"SP": "BBB+/Stable", "Fitch": "BBB/Stable（EthiFinance）"},
            "distance_from_threshold": "S&P BBB+/Stable — 正好達到 Siegfried 門檻下限，Stable 展望",
            "downgrade_risk": "低（短期）。S&P 展望穩定，預計 2026 FCF ~€636M，Stage 1 應收款。主要風險為治理爭議升級影響 US 市場准入。",
            "governance_status": "Sinochem 持股降至 20.1%（Lumina Crown 接手 14%）。義大利黃金力量限制 Sinochem 在 9.99% 以上的投票及董事會影響力。3 名中方董事於 9 月業績上投票反對。股東協議 2026-05 已到期。US Cyber Tyre 銷售准入已獲批。",
            "siegfried_exposure": "無基金敞口",
            "web_search_findings": "治理風險被義大利監管及 Sinochem 股份出售部分遏制。S&P 評級穩定，FCF 強勁。應收款目前無異常。",
            "recommended_action": "MONITOR",
            "action_detail": "Pirelli 信用評級 BBB+/Stable 符合 Siegfried 門檻。主要風險為治理（非信用）：Sinochem 若重新干預或中方董事對立加劇，可能引發管理不穩定。現無 Siegfried 敞口，建議每季確認治理進展及 Sinochem 股份出售最新狀況。",
            "monitoring_frequency": "每季（治理動態）"
        }
    ],
    "proactive_risks": [
        {
            "company": "LG Chem Ltd.",
            "note": "已納入 HIGH severity 分析，同時屬 proactive risk（現評級低於 Siegfried 門檻）"
        }
    ]
}

data['whitelist_deep_analysis'] = wl_analysis

# === 更新 UnitedHealth 持續監控 ===
data['continuous_monitor'] = [
    {
        "name": "UnitedHealth Group",
        "ticker": "UNH US",
        "has_alert": False,
        "alert_count": 0,
        "current_ratings": {
            "SP": "A+/Negative",
            "Moodys": "Negative outlook（確認 A 層級）",
            "Fitch": "A/Negative",
            "AM_Best": "Affirmed 2026-08"
        },
        "distance_from_threshold": "S&P A+ 高於 BBB+ 達 4 個 notch，遠離 Sub-IG 區間",
        "doj_investigation": {
            "status": "持續中，無結果",
            "latest": "2025-07-24 UNH 披露配合 DOJ 刑事及民事調查（Medicare Advantage）。截至 2026-11-06 無新行動、無起訴、無和解。",
            "congressional": "2026-01 參議院報告指控 UNH 透過家訪評估及圖表審查拉高 MA 風險分數。",
            "cms_impact": "CMS 擬 2027 年起排除特定「unlinked」圖表審查診斷於 MA 風險計算，料影響收入。",
            "texas_ag": "Texas AG Ken Paxton 於 2026-10 展開調查（保障範圍拒絕問題）",
            "investor_lawsuit": "2026-09-30 投資人訴訟推進中（指控製造盈利數字掩蓋利潤下滑）"
        },
        "credit_risk_assessment": "S&P 表示若槓桿無法改善至 ~40% 或法律/監管風險惡化，將考慮降評一個 notch（A+ → A）。距 BBB+/Baa1 仍有 3-4 個 notch 緩衝，SCF 敞口影響甚微。",
        "siegfried_exposure": "待確認（需查 AllFundsHistory）",
        "scf_impact": "目前為 MEDIUM 關注級別。UNH 信用遠優於門檻，主要風險為監管罰款對現金流的長期侵蝕。",
        "recommended_action": "MONITOR",
        "monitoring_frequency": "每週（DOJ 動態 + 季度業績）",
        "next_milestone": "UNH Q4 2026 財報（預計 2027-01）；DOJ 是否採取正式行動"
    }
]

data['analysis_completed_at'] = datetime.now().isoformat()
data['analysis_version'] = "TARS5-2026-11-07-v1"

with open('/tmp/case3_analysis_2026-11-07.json', 'w', encoding='utf-8') as f:
    json.dump(data, f, ensure_ascii=False, indent=2)

print("✓ JSON updated successfully")
print(f"  Total alerts: {len(data['alerts'])}")
print(f"  WhiteList HIGH findings: {len(data['whitelist_deep_analysis']['high_severity'])}")
print(f"  Continuous monitors: {len(data['continuous_monitor'])}")
