import streamlit as st
import subprocess
import time

# ---------- 頁面設定 ----------
st.set_page_config(page_title="RPi 5 Monitor", layout="wide")  # 頁面標題與布局

# 自訂 CSS 樣式
st.markdown(
    """
<style>
.block-container { padding-top: 2rem; }  /* 頁面上方間距 */
div[data-testid="metric-container"] {
    background-color: #0e1117;
    border: 1px solid #1f2937;
    padding: 1rem;
    border-radius: 12px;
    color: white;
}
.temp-warn {
    background-color: #7f1d1d !important;
    border-color: #ef4444 !important;
}
</style>
""",
    unsafe_allow_html=True,
)

st.title("🍓 Raspberry Pi 5 · 系統監控")  # 標題

# ---------- 輔助函數 ----------
def run(cmd):
    """執行系統指令並返回結果 (去除換行)"""
    return subprocess.check_output(cmd, shell=True, text=True).strip()


# ---------- CPU 使用率 ----------
def cpu_usage():
    """取得 CPU 使用率"""
    idle = run(
        "top -bn1 | grep 'Cpu(s)' | "
        "sed 's/,/ /g' | "
        "awk '{for(i=1;i<=NF;i++) if ($i==\"id\") print $(i-1)}'"
    )
    return 100 - float(idle)


# ---------- RAM 使用率 ----------
def ram_usage():
    """取得 RAM 已用量、總量、使用率"""
    used, total, percent = run(
        "free -m | awk 'NR==2{print $3,$2,$3/$2*100}'"
    ).split()
    return int(used), int(total), float(percent)


# ---------- Swap 使用率 ----------
def swap_usage():
    """取得 Swap 已用量、總量、使用率"""
    used, total, percent = run(
        "free -m | awk 'NR==3{print $3,$2,($3/$2)*100}'"
    ).split()
    return int(used), int(total), float(percent)


# ---------- 磁碟使用率 ----------
def disk_usage():
    """取得根目錄磁碟使用量"""
    used, total, percent = run(
        "df -h / | awk 'NR==2{print $3,$2,$5}'"
    ).split()
    return used, total, percent


# ---------- CPU 溫度 ----------
def cpu_temp():
    """取得 CPU 溫度"""
    temp = run("vcgencmd measure_temp | cut -d= -f2 | tr -d \"'C\"")
    return float(temp)


# ---------- 網路使用量 ----------
def net_usage():
    """取得主要網卡名稱與上下行流量 (MB)"""
    iface = run(
        "ip -o link show | awk -F': ' '{print $2}' | "
        "grep -E '^(eth|wlan|usb)' | head -n1"
    )
    rx, tx = run(
        f"cat /proc/net/dev | grep {iface} | "
        "awk '{print $2,$10}'"
    ).split()
    return iface, int(tx) // 1024**2, int(rx) // 1024**2


# ---------- 使用者介面 ----------
c1, c2, c3, c4, c5, c6 = st.columns(6)

# CPU
c1.metric("🧠 CPU", f"{cpu_usage():.0f} %")

# RAM
ram_used, ram_total, ram_pct = ram_usage()
c2.metric("💾 RAM", f"{ram_pct:.0f} %", f"{ram_used} / {ram_total} MB")

# Swap
swap_used, swap_total, swap_pct = swap_usage()
c3.metric("🌀 Swap", f"{swap_pct:.0f} %", f"{swap_used} / {swap_total} MB")

# 磁碟
disk_used, disk_total, disk_pct = disk_usage()
c4.metric("📀 Disk", disk_pct, f"{disk_used} / {disk_total}")

# CPU 溫度
temp = cpu_temp()
if temp >= 80:  # 超過 80°C 顯示警告
    html_temp_warn = f"""<div class="temp-warn" style="padding:1rem;border-radius:12px">
🌡 <b>Temp</b><br>
<span style="font-size:2rem">{temp:.1f} °C</span><br>
⚠️ OVERHEAT
</div>"""
    c5.markdown(html_temp_warn, unsafe_allow_html=True)
else:
    c5.metric("🌡 Temp", f"{temp:.1f} °C")

# 網路流量
iface, tx, rx = net_usage()
c6.metric("🌐 Net", f"{iface} ↑ {tx} MB", f"↓ {rx} MB")

# ---------- 自動刷新 ----------
time.sleep(2)
st.rerun()