#!/usr/bin/env python3

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

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

# --- 1. 設置標準 CGI 輸出標頭 ---
#print("Content-Type: text/html\n")
print("Content-Type: text/html; charset=UTF-8\n")
# 上面是 CGI 必須的第一行輸出，告訴瀏覽器返回的是 HTML 內容

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

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

    # 提取並處理數據
    try:
        alpha = float(form.getvalue("alpha"))
        df = int(form.getvalue("df"))
        test_type = form.getvalue("test_type")

        if df <= 0 or alpha not in [0.1, 0.05, 0.01] or test_type not in ['l', 'r', 'd']:
            print("<p style='color:red;'>輸入數據無效，請檢查 alpha, df 或檢定類型。</p>")
            display_form()
            return

        # 根據檢定類型計算累積機率 P
        if test_type == 'l':
            cumulative_prob = alpha
            test_type_str = "左尾檢定"
            t_crit = t.ppf(cumulative_prob, df)

        elif test_type == 'r':
            cumulative_prob = 1 - alpha
            test_type_str = "右尾檢定"
            t_crit = t.ppf(cumulative_prob, df)

        elif test_type == 'd':
            cumulative_prob_positive = 1 - alpha / 2
            test_type_str = "雙尾檢定"
            t_crit_positive = t.ppf(cumulative_prob_positive, df)
            t_crit_negative = -t_crit_positive

        # 顯示計算結果
        print(f"<h2>t 臨界值計算結果</h2>")
        print(f"<p>顯著性水平 (alpha): {alpha}</p>")
        print(f"<p>自由度 (df): {df}</p>")
        print(f"<p>檢定類型: {test_type_str}</p>")
        print("<hr>")

        if test_type == 'd':
            print(f"<p>t 臨界值 (+): <strong>{t_crit_positive:.4f}</strong></p>")
            print(f"<p>t 臨界值 (-): <strong>{t_crit_negative:.4f}</strong></p>")
            print(f"<p>決策區間: t 統計量 < {t_crit_negative:.4f} 或 t 統計量 > {t_crit_positive:.4f}</p>")
        else:
            print(f"<p>t 臨界值: <strong>{t_crit:.4f}</strong></p>")
            if test_type == 'l':
                print(f"決策規則: t 統計量 < {t_crit:.4f} 時，拒絕 H0。")
            else:
                print(f"決策規則: t 統計量 > {t_crit:.4f} 時，拒絕 H0。")
        print("<br><p><a href='t_calc.py'>重新計算</a></p>")

    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>t 臨界值計算器 (CGI)</title>
    </head>
    <body>
    <div align="center">
        <h1>t 臨界值計算器</h1>
        (20251026 <a href="../../../../day/h_20251001a.html" target="_blank">洪哲文</a> for phd24_QM_I class)
        <hr>
        <form method="post" action="htw_t_calc.py">

            <label for="alpha">1. Alpha (α):</label>
            <select name="alpha" required>
                <option value="0.1">0.1</option>
                <option value="0.05" selected>0.05</option>
                <option value="0.01">0.01</option>
            </select><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="d">雙尾 (d)</option>
                <option value="r">右尾 (r)</option>
                <option value="l">左尾 (l)</option>
            </select><br><br>

            <input type="submit" value="計算臨界值">
        </form>
    </div>
    </body>
    </html>
    """)

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