#!/usr/bin/env python3

# --- 導入所需模組 ---
import cgi
import cgitb
import numpy as np
from scipy.stats import t

# 啟用 CGI 錯誤報告，這對於除錯非常重要
cgitb.enable()

# --- 1. 設置標準 CGI 輸出標頭 ---
# 必須明確指定 charset=UTF-8，否則中文會亂碼
print("Content-Type: text/html; charset=UTF-8\n")

# --- 2. 核心計算邏輯 ---
def calculate_p_value():
    # 獲取表單數據
    form = cgi.FieldStorage()

    # 檢查是否提交了數據
    if "t_value" not in form:
        # 如果沒有數據，顯示輸入表單
        display_form()
        return

    # 提取並處理數據
    try:
        t_value = float(form.getvalue("t_value"))
        df = int(form.getvalue("df"))
        test_type = form.getvalue("test_type") # '1' for one-tailed, '2' for two-tailed

        if df <= 0 or test_type not in ['1', '2']:
            print("<p style='color:red;'>輸入數據無效，自由度必須大於 0，檢定類型必須是 1 或 2。</p>")
            display_form()
            return

        # 核心計算：使用 scipy.stats.t.sf (Survival Function) 計算單尾機率 P(T > |t|)
        abs_t = np.abs(t_value)
        right_tail_prob = t.sf(abs_t, df)

        if test_type == '1':
            # 單尾 p-value = 單尾機率
            p_value = right_tail_prob
            test_type_str = "單尾檢定"
        else:
            # 雙尾 p-value = 2 * 單尾機率
            p_value = 2 * right_tail_prob
            test_type_str = "雙尾檢定"

        # 顯示計算結果
        print(f"<h2>t 統計量 p-value 計算結果</h2>")
        print(f"<p>t 統計量 (t-value): {t_value}</p>")
        print(f"<p>自由度 (df): {df}</p>")
        print(f"<p>檢定類型: {test_type_str}</p>")
        print("<hr>")

        # 輸出 p-value
        print(f"<p style='font-size: 1.2em;'>計算結果 p-value: <strong>{p_value:.6f}</strong></p>")

        # 決策參考 (alpha = 0.05)
        decision_text = ""
        if p_value < 0.05:
            decision_text = "在 5% 顯著性水平下，結果是統計上顯著的 (p < 0.05)。"
        else:
            decision_text = "在 5% 顯著性水平下，結果是非統計上顯著的 (p ≥ 0.05)。"

        print(f"<p style='color: {'green' if p_value < 0.05 else 'blue'};'>{decision_text}</p>")

        print("<br><p><a href='p_calc.py'>重新計算</a></p>")

    except ValueError:
        print("<p style='color:red;'>輸入數據格式錯誤，t 統計量和自由度必須為數字。</p>")
        display_form()
    except Exception as e:
        print(f"<p style='color:red;'>處理數據時發生未預期錯誤: {e}</p>")
        display_form()

# --- 3. HTML 表單（用於輸入） ---
def display_form():
    """生成包含輸入欄位的 HTML 表單。"""
    print("""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>p-value計算器(CGI)</title>
    </head>
    <body>
    <div align="center">
        <h1>t 統計量 p-value 計算器</h1>
        (20251026 <a href="../../../../day/h_20251001a.html" target="_blank">洪哲文</a> for phd24_QM_I class)
        <hr>
        <form method="post" action="htw_p_calc.py">

            <label for="t_value">1. t 統計量 (t-value):</label>
            <input type="number" step="any" name="t_value" required><br><br>

            <label for="df">2. 自由度 (df):</label>
            <input type="number" name="df" min="1" required><br><br>

            <label for="test_type">3. 檢定類型:</label>
            <select name="test_type" required>
                <option value="2" selected>2: 雙尾檢定</option>
                <option value="1">1: 單尾檢定</option>
            </select><br><br>

            <input type="submit" value="計算 p-value">
        </form>
    </div>
    </body>
    </html>
    """)

# --- 4. 主執行區塊 ---
if __name__ == "__main__":
    calculate_p_value()
