#!/usr/bin/env python3
"""每日台股收盤價抓取器 — 使用 yfinance"""
import sqlite3, os, sys
from datetime import datetime, date

DB_PATH = os.path.expanduser("~/.hermes/profiles/finance-butler/finance.db")

# 持股：資料庫代號 -> Yahoo Finance symbol
HOLDINGS = {
    '1503': '1503.TW',  # 士電
    '1519': '1519.TW',  # 華城
    '2303': '2303.TW',  # 聯電
    '2330': '2330.TW',  # 台積電
    '2337': '2337.TW',  # 旺宏
    '2344': '2344.TW',  # 華邦電
    '3037': '3037.TW',  # 南亞科
    '2603': '2603.TW',  # 長榮
    '2634': '2634.TW',  # 漢翔
}

def fetch_and_save():
    try:
        import yfinance as yf
    except ImportError:
        print("yfinance not installed. Run: pip install yfinance --break-system-packages")
        sys.exit(1)

    today = date.today().strftime('%Y-%m-%d')
    symbols = list(HOLDINGS.values())

    print(f"抓取台股收盤價 {today}...")
    tickers = yf.Tickers(' '.join(symbols))

    con = sqlite3.connect(DB_PATH)
    cur = con.cursor()
    saved = 0

    for db_sym, yf_sym in HOLDINGS.items():
        try:
            t = tickers.tickers[yf_sym]
            info = t.fast_info
            close = info.last_price
            prev = info.previous_close
            if not close:
                continue
            change = round(close - prev, 2) if prev else 0
            change_pct = round((change / prev) * 100, 2) if prev else 0
            name = t.info.get('shortName', db_sym)

            cur.execute("""
                INSERT OR REPLACE INTO stock_prices (symbol, date, close_price, change_amount, change_percent)
                VALUES (?,?,?,?,?)
            """, (db_sym, today, close, change, change_pct))
            saved += 1
            arrow = '▲' if change >= 0 else '▼'
            print(f"  {name}({db_sym}): {close:.1f} {arrow}{abs(change):.1f} ({change_pct:+.2f}%)")
        except Exception as e:
            print(f"  {db_sym}: 抓取失敗 ({e})")

    con.commit()
    con.close()
    print(f"\n✓ 已儲存 {saved} 支股票")
    return saved

if __name__ == '__main__':
    fetch_and_save()
