import json, datetime

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

# --- Alert analyses ---
alert_analyses = {
    5: {  # Marks & Spencer
        "analysis": "S&P 於 2026-11-12 將展望由穩定改為正面，維持 BBB-/A-3 評等。M&S 財務改善強勁：Food 表現提升、Fashion/Home/Beauty 復甦，調整槓桿約 1.8x，FFO/debt ~43%。12-24 個月內若維持調整槓桿低於 2.0x 且 FFO/debt 超過 45%，有望升至 BBB。",
        "scf_impact": "無 Siegfried 持倉，改善訊號，與 SCF 業務無直接影響。",
        "risk_level": "low",
        "recommended_action": "MONITOR — 資訊性，無需操作。正面評等動向。",
        "verification_level": "HIGH（S&P 官方行動，直接確認）"
    },
    8: {  # Yara Stable
        "analysis": "Moody's 維持 Baa2/穩定展望。Yara 財務政策謹慎，目標淨債/EBITDA 1.5-2.0x，淨債/股本低於 0.60x。截至 2026-09-30 總債務約 $3.29B。",
        "scf_impact": "無 Siegfried 持倉，肥料/農業化學品產業，SCF 無直接相關。",
        "risk_level": "low",
        "recommended_action": "MONITOR — 資訊性，新評等啟動確認，穩定訊號。",
        "verification_level": "HIGH（Moody's 官方行動）"
    },
    9: {  # Yara initiated
        "analysis": "Moody's 首次啟動 Baa2 長期評等（Stable）。Baa2 = 投資等級中段，高於 Siegfried BBB+/Baa1 門檻 1 個級距（Baa1 = BBB+）。",
        "scf_impact": "無 Siegfried 持倉，啟動評等屬中性至正面訊號。",
        "risk_level": "low",
        "recommended_action": "MONITOR — 資訊性，啟動評等確認為投資等級。",
        "verification_level": "HIGH（Moody's 官方行動）"
    },
    10: {  # Komatsu
        "analysis": "Komatsu 收購 Astec Industries 道路施工設備業務（Roadtec + Carlson 品牌），企業價值 USD 7,500 萬，預計 2027 Q1 完成。規模小，補強型策略收購。Komatsu 信用質量穩健，日本重型設備龍頭。",
        "scf_impact": "SCP5 持倉 USD 14,646,612。收購為正面策略訊號：擴大道路設備業務，不影響 Komatsu 核心財務結構或 Siegfried 敞口安全性。",
        "risk_level": "low",
        "recommended_action": "MONITOR — 正面訊號，SCP5 敞口安全，無需操作。",
        "verification_level": "HIGH（多來源交叉確認，Komatsu 官網 + 媒體）"
    },
    13: {  # Assa Abloy
        "analysis": "Assa Abloy 收購巴西 Rometal 傢俱零件廠（2026年第 11 筆收購）。S&P 於 2026-04-02 將展望由負面改為穩定，維持 A-/A-2。九個月收購合計 SEK 51.43 億，槓桿調整債務/EBITDA 低於 2.5x。",
        "scf_impact": "四基金合計敞口 USD 24,735,749（SCP2+SCP4+SCP5+SCP6-2）。信用狀況改善（展望轉穩定），收購為小規模補強型，不影響信用結構。敞口安全。",
        "risk_level": "low",
        "recommended_action": "MONITOR — 信用改善中，敞口安全，無需操作。",
        "verification_level": "HIGH（S&P 官方行動 + 公司季報）"
    }
}

for alert in data['alerts']:
    idx = alert['index']
    if idx in alert_analyses:
        alert.update(alert_analyses[idx])
    elif not alert.get('analysis'):
        alert['analysis'] = "無 Siegfried 持倉，社交情緒或併購有效日期更新，資訊性。"
        alert['scf_impact'] = "無直接影響。"
        alert['risk_level'] = "low"
        alert['recommended_action'] = "MONITOR — 資訊性。"
        alert['verification_level'] = "MEDIUM"

# --- WhiteList analysis section ---
data['whitelist_analysis'] = {
    "run_date": "2026-11-13",
    "high_severity": [
        {
            "company": "Volkswagen AG",
            "funds": ["SCP2", "SCP5", "SCP6-2"],
            "current_ratings": {
                "sp": "BBB+/Negative",
                "moodys": "Baa1/Stable",
                "dbrs": "BBB(high)/Stable (downgraded from A(low) 2026-07-30)",
                "fitch": "A-/Negative"
            },
            "siegfried_threshold": "BBB+/Baa1",
            "distance_to_threshold": "S&P BBB+ = 正好在門檻邊緣；負面展望意味 12-24 個月內降至 BBB 的風險實質存在。若 BBB，跌破 Siegfried 門檻。Moody's Baa1 = 高於門檻 1 個級距，穩定。",
            "downgrade_risk": "HIGH — S&P 和 Fitch 均持負面展望，DBRS 已於 7 月降評一個檔次。若重組失敗、中國市場持續虧損或 FCF 持續負值，12 個月內 S&P 降至 BBB 的可能性實質存在。",
            "mandatory_exit_note": "若 S&P 或 DBRS 降至 BBB-（S&P）/ BBB(low)（DBRS），Siegfried 需強制評估退出 SCP2/SCP5/SCP6-2 對 VW 的持倉。",
            "scf_risk_assessment": "中高風險。VW AG 當前仍為合格投資等級 SCF 交易對手，但負面展望 + DBRS 已降評 + 貿易應收款可疑帳款升至 €7.16 億，SCF 敞口須加強監控。BBB-/BB+ 為紅線。",
            "search_sources": ["spglobal.com", "volkswagen-group.com", "fitchratings.com", "dbrs.com"],
            "recommendation": "INVESTIGATE",
            "action_items": [
                "立即確認 SCP2/SCP5/SCP6-2 對 VW AG 的未清償敞口金額及到期日",
                "追蹤 S&P 是否在 Q4 2026 財報後執行進一步評等動作",
                "與 Silver 討論是否有觸發條款需要在 BBB 時啟動",
                "區分 VW AG / VW Financial Services AG / VW Bank GmbH 各法律實體評等差異"
            ]
        }
    ],
    "proactive_risks": [
        {
            "company": "UnitedHealth Group Inc.",
            "funds": ["SCP2", "SCP5", "SCP6-2"],
            "current_ratings": {"sp": "A+/Negative", "moodys": "Negative outlook（確認）"},
            "distance_to_threshold": "A+ 遠高於 BBB+ 門檻（相差 6 個級距），短期無降評至門檻風險",
            "negative_outlook": "是 — S&P 和 Moody's 雙負面展望",
            "downgrade_condition": "若槓桿未在 12-24 個月內回落至約 40% 目標，S&P 可能降評",
            "monitor_frequency": "每週",
            "note": "訴訟組合廣但核心財務穩健（Q3 淨利 $4.1-4.3B）"
        },
        {
            "company": "Target Corp.",
            "funds": ["SCF", "SCP2", "SCP6-2"],
            "current_ratings": {"sp": "A", "moodys": "A2", "fitch": "A（已撤回）"},
            "distance_to_threshold": "A/A2 遠高於 BBB+ 門檻（相差 4-5 個級距）",
            "negative_outlook": "Fitch 負面（已撤回），S&P/Moody's 無負面展望",
            "downgrade_condition": "11-18 Q3業績後若指引大幅下調或FCF惡化",
            "monitor_frequency": "每月（11-18 業績日後重新評估）",
            "note": "11月18日業績日為關鍵觀察點"
        },
        {
            "company": "Walt Disney Co.",
            "funds": ["SCP2", "SCP5", "SCP6-2"],
            "current_ratings": {"sp": "A/Stable", "moodys": "A2/Stable"},
            "distance_to_threshold": "A/A2 遠高於 BBB+ 門檻（相差 4 個級距）",
            "negative_outlook": "否 — S&P 和 Moody's 均為穩定展望",
            "downgrade_condition": "若槓桿超過 S&P ~2.5x 容忍度或現金流持續惡化",
            "monitor_frequency": "每月",
            "note": "FY2026 Q4 業績後確認自由現金流與指引差距"
        },
        {
            "company": "Vulcan Materials Co.",
            "funds": ["SCP2", "SCP5", "SCP6-2"],
            "current_ratings": {
                "sp": "⚠️ 疑似已降評（2026-03-02 降評動作確認，新評等未能核實；前評等 BBB+）",
                "fitch": "BBB+/Stable（2026-06-18 確認）",
                "moodys": "Baa2（前記錄，無 2026 動作）"
            },
            "distance_to_threshold": "⚠️ 若 S&P 新評等為 BBB，已跌破 Siegfried BBB+ 門檻（相差 1 個級距）",
            "negative_outlook": "待確認 — S&P 新評等及展望未知",
            "downgrade_condition": "S&P 降評事實已發生（2026-03），需確認現行評等",
            "monitor_frequency": "每週（需Derek直接查核S&P當前評等）",
            "note": "⚠️ WhiteList 現有記錄 'BBB+（S&P）' 可能已過時，建議直接查核"
        },
        {
            "company": "Bayer AG",
            "funds": [],
            "current_ratings": {"sp": "BBB/Negative", "fitch": "BBB/Negative"},
            "distance_to_threshold": "BBB 低於 Siegfried BBB+ 門檻 1 個級距，現無基金敞口",
            "negative_outlook": "是 — S&P 和 Fitch 雙負面展望",
            "downgrade_condition": "若和解未獲批或訴訟付款超出預期，降至 BBB- 風險",
            "monitor_frequency": "每月",
            "note": "無基金敞口，不建議新增直至評等改善至 BBB+；追蹤 Roundup 和解 Missouri 法院裁決"
        }
    ]
}

# --- Update continuous_monitor ---
data['continuous_monitor'] = [
    {
        "name": "UnitedHealth Group",
        "has_alert": False,
        "alert_count": 0,
        "doj_investigation_status": "進行中 — civil + criminal 請求，尚無起訴或不當行為認定（截至 2026-11-12）",
        "investigation_focus": "Medicare Advantage 風險調整編碼/upcoding，聚焦家訪診斷、圖表審查、提供者激勵機制",
        "unh_response": "主動聯繫 DOJ，配合調查，FTI 報告顯示 96.6% 家訪診斷有醫療記錄支持",
        "current_ratings": {"sp": "A+/Negative", "moodys": "Negative outlook"},
        "scf_risk_assessment": "低至中 — A+ 遠高於 BBB+ 門檻，核心財務穩健（Q3 淨利 $4.1-4.3B），但雙負面展望需每週監控",
        "escalate_condition": "若 DOJ 提出正式起訴或民事和解金額超過 $5B，立即升格 ESCALATE 並通報 Silver",
        "funds_exposure": ["SCP2", "SCP5", "SCP6-2"],
        "search_date": "2026-11-13",
        "sources": ["DOJ官方聲明", "UNH新聞稿", "WSJ", "medicaleconomics.com"]
    }
]

data['analysis_completed_at'] = datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8))).isoformat()
data['analysis_version'] = "v2 — web_search enriched 2026-11-13"

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

print("✓ JSON updated successfully")
