#!/usr/bin/env python
# coding: utf-8

"""
@author: Emily
@edit & optimized：Scott

道路风险预测系统
功能：完整的STGCN模型加载、数据预处理和预测流程

5-class STGCN classification of composite risk index (classes 1‥5).

X = weather (temp, humidity, rainfall, wind) + all POIs + FMS warning label
Y = risk-index class 1,2,3,4,5
"""

# === 基础库 ===
import numpy as np  # 数值计算库，提供多维数组支持
import pandas as pd  # 数据分析库，提供DataFrame数据结构
import torch  # PyTorch深度学习框架
import torch.nn as nn  # PyTorch神经网络模块
from sklearn.preprocessing import StandardScaler  # 数据标准化(Z-score)工具
import warnings  # Python警告控制模块
warnings.filterwarnings("ignore",  # 忽略特定警告
    category=UserWarning,  # 忽略UserWarning类警告
    message="Unable to retrieve source for @torch.jit._overload")  # 忽略特定警告信息
import os, sys  # 操作系统接口模块
sys.path.append(os.path.abspath(r'./library'))  # 将./library目录添加到模块搜索路径
os.environ['PYTHONWARNINGS'] = "ignore::UserWarning"  # 设置环境变量忽略UserWarning
from pathlib import Path  # 面向对象的文件系统路径操作
from stgcn import STGCN  # 时空图卷积网络实现类
from utils import get_normalized_adj  # 图结构邻接矩阵归一化工具

# === 配置参数 ===
# BASE_DIR = Path(os.getcwd()).absolute()  # py交互环境
BASE_DIR = Path(__file__).parent.absolute()  # py打包环境
CONFIG = {  # 项目配置字典
    't_in': 12,  # 输入时间步长
    't_out': 2,  # 输出时间步长
    'batch_size': 16,  # 训练批次大小
    'learning_rate': 0.001,  # 学习率
    'num_classes': 5,  # 分类类别数
    'num_nodes': 13281,  # 图节点数量
    'data_paths': {  # 数据文件路径配置
        'adj_matrix': str(BASE_DIR / "data/Dependence_data/road_matrix_13281.csv"),  # 邻接矩阵文件路径
        'accidents': str(BASE_DIR / "data/Dependence_data/accidents+allPOIs_per_segment(13281).csv"),  # 事故数据文件路径
        'rainfall': str(BASE_DIR / "data/Weather_data/rainfall.csv"),  # 降雨数据文件路径
        'wind': str(BASE_DIR / "data/Weather_data/wind.csv"),  # 风速数据文件路径
        'temperature': str(BASE_DIR / "data/Weather_data/temperature.csv"),  # 温度数据文件路径
        'humidity': str(BASE_DIR / "data/Weather_data/humidity.csv"),  # 湿度数据文件路径
        'warning_labels': str(BASE_DIR / "data/Dependence_data/13281segments_warning_labels.csv")  # 预警标签文件路径
    }
}

# === 工具函数 ===
def check_tensor(t, name):
    """检查张量中的NaN/Inf值"""
    if isinstance(t, torch.Tensor):
        if torch.isnan(t).any(): print(f"NaN in {name}")
        if torch.isinf(t).any(): print(f"Inf in {name}")
    elif isinstance(t, np.ndarray):
        if np.isnan(t).any(): print(f"NaN in {name}")
        if np.isinf(t).any(): print(f"Inf in {name}")

def _resolve_path(relative_path):
    """将相对路径解析为绝对路径"""
#    base_dir = Path(os.getcwd()).absolute()  # py交互环境
    base_dir = Path(__file__).parent.absolute()  # py打包环境
    return str(base_dir / relative_path)
'''
def load_adjacency_matrix(path, seg_ids):
    """加载邻接矩阵并添加自环"""
    A = np.genfromtxt(_resolve_path(path), delimiter=',', dtype=np.float32)
    if A.shape[0] != A.shape[1]:
        raise ValueError("Adjacency matrix must be square.")
    A = A + np.eye(A.shape[0], dtype=np.float32)
    return A[np.ix_(seg_ids, seg_ids)]
'''

def load_adjacency_matrix(path, seg_ids):
    abs_path = _resolve_path(path)
    df = pd.read_csv(abs_path, header=None, dtype=float, engine="python")
    # 去除全空列/行
    df = df.dropna(axis=0, how="all").dropna(axis=1, how="all")
    # 对齐为方阵
    side = min(df.shape[0], df.shape[1])
    if df.shape[0] != df.shape[1]:
        print(f"[Adjacency] 警告：矩阵非方阵 {df.shape}，已裁剪为 {side}×{side}")
    A = df.iloc[:side, :side].to_numpy(dtype=np.float32)
    A = A + np.eye(A.shape[0], dtype=np.float32)
    if np.max(seg_ids) >= A.shape[0]:
        raise ValueError(f"seg_ids 最大索引 {np.max(seg_ids)} 超出邻接矩阵大小 {A.shape[0]}")
    return A[np.ix_(seg_ids, seg_ids)]

def load_data(accident_file, rainfall_file, wind_file, temp_file, humidity_file, seg_ids):
    """
    Returns
      X : (N, F, T)  – features
    """
    # -------- weather ------------------------------------------------
    def _load_ts(fp):
        arr = np.genfromtxt(fp, delimiter=',', encoding='utf-8', skip_header=1).T[seg_ids, :].astype(np.float32)
        # PATCH: Fill NaN/Infs in weather data
        arr = np.nan_to_num(arr, nan=0.0, posinf=0.0, neginf=0.0)
        return arr

    rainfall = _load_ts(_resolve_path(rainfall_file))
    wind = _load_ts(_resolve_path(wind_file))
    temp = _load_ts(_resolve_path(temp_file))
    humidity = _load_ts(_resolve_path(humidity_file))

    # -------- static POIs + warning label ---------------------------
    node_df = pd.read_csv(accident_file)
    node_df = node_df[node_df['Segment_ID'].isin(seg_ids)].copy()
#    warn_df = pd.read_csv(_resolve_path(r"data/Dependence_data/13281segments_warning_labels.csv"),
#                     encoding='utf-8')  # py交互环境
    warn_df = pd.read_csv(_resolve_path(r"./data/Dependence_data/13281segments_warning_labels.csv"),
                     encoding='utf-8')  # py打包环境
    node_df = node_df.merge(warn_df, on='Segment_ID', how='left')
    node_df['warning_label'] = node_df['warning_label'].fillna(0)

    node_df = node_df.set_index('Segment_ID').loc[seg_ids]
    static_cols = [c for c in node_df.columns if c != 'Segment_ID']
    static_mat  = node_df[static_cols].to_numpy(dtype=np.float32)        # (N, P)

    # PATCH: Remove zero-variance columns to avoid division by zero
    stds = static_mat.std(axis=0)
    non_zero_var = stds > 1e-6
    if not np.all(non_zero_var):
        print(f"Removed {np.sum(~non_zero_var)} zero-variance features from static_mat.")
    static_mat = static_mat[:, non_zero_var]

    # PATCH: Fill any remaining NaN/Infs in static_mat
    static_mat = np.nan_to_num(static_mat, nan=0.0, posinf=0.0, neginf=0.0)

    scaler = StandardScaler()
    static_mat = scaler.fit_transform(static_mat)

    # PATCH: Check for NaN/Inf after scaling
    if np.isnan(static_mat).any() or np.isinf(static_mat).any():
        print("NaN/Inf in static_mat after normalization! Filling with 0.")
        static_mat = np.nan_to_num(static_mat, nan=0.0, posinf=0.0, neginf=0.0)

    T = rainfall.shape[1]
    static_stack = np.repeat(static_mat[:, :, None], T, axis=2)          # (N, P, T)

    # -------- assemble X --------------------------------------------
    X_dyn  = np.stack([rainfall, wind, temp, humidity], axis=1)          # (N, 4, T)
    X      = np.concatenate([X_dyn, static_stack], axis=1)               # (N, 4+P, T)

    # PATCH: Fill any NaN/Infs in final X
    X = np.nan_to_num(X, nan=0.0, posinf=0.0, neginf=0.0)

    # PATCH: Check for NaN/Inf
    check_tensor(X, 'X (final)')

    return X

def gen_dataset(X, t_in, t_out):
    """
    Sliding-window samples for input X.
      returns:
        X_win : (S, N, F, t_in)
    """
    N, F, T = X.shape
    S = T - t_in - t_out + 1
    if S <= 0:
        raise ValueError("Not enough timesteps.")
    X_win = np.lib.stride_tricks.sliding_window_view(X, window_shape=t_in, axis=2)
    X_win = X_win[:, :, :S, :].transpose(2, 0, 1, 3)                    # (S, N, F, t_in)

    # PATCH: Fill NaN/Inf in windowed data
    X_win = np.nan_to_num(X_win, nan=0.0, posinf=0.0, neginf=0.0)
    check_tensor(X_win, 'X_win')
    return torch.from_numpy(X_win).float()

# === 主程序 ===
def main():
    # 初始化
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    seg_ids = np.arange(CONFIG['num_nodes'], dtype=int)

    # 数据加载
    print("Loading data...")
    A = load_adjacency_matrix(CONFIG['data_paths']['adj_matrix'], seg_ids)
    check_tensor(A, 'Adjacency matrix')
    X = load_data(accident_file=CONFIG['data_paths']['accidents'],
                rainfall_file=CONFIG['data_paths']['rainfall'],
                wind_file=CONFIG['data_paths']['wind'],
                temp_file=CONFIG['data_paths']['temperature'],
                humidity_file=CONFIG['data_paths']['humidity'],
                seg_ids=seg_ids)

    # 数据预处理
    A_hat = torch.from_numpy(get_normalized_adj(A)).float()
    tr_in = gen_dataset(X, CONFIG['t_in'], CONFIG['t_out'])

    # 模型预测
    print("Loading model...")
    model = torch.load(_resolve_path('./model/full_risk_model_30min.pth'),
                  map_location=device,
                  weights_only=False).to(device)
    print("Predicting...")
    model.eval()
    with torch.no_grad():
        pred = model(A_hat.to(device), tr_in.to(device)).argmax(-1).cpu()
        pred_plus1 = pred + 1  # 将0‥4转换为1‥5
    print("Predict complete")

    # 保存结果
    print("Transform data...")
    output = pd.DataFrame(
        #pred.squeeze(0).T.numpy(),
        pred_plus1.squeeze(0).T.numpy(),  # 使用加1后的结果
        columns=pd.read_csv(CONFIG['data_paths']['rainfall'], nrows=0).columns.tolist()
    )
    print("Transform complete")
    # py打包环境
    print("Trying save prediction...")
    try:
        if getattr(sys, 'frozen', False):
            base_path = Path.cwd()
        else:
            base_path = Path(sys.executable).parent  # 使用可执行文件所在目录
        target_dir = base_path / "output"
        target_dir.mkdir(parents=True, exist_ok=True)  # 确保使用Path对象操作
        output_path = target_dir / "output.csv"

        print("Prediction saving...")
        output.to_csv(str(output_path), index=False)  # 仅在保存时转为字符串
        print(f"Prediction saved to {output_path}")
        print("Done!")
    except Exception as e:
        print(f"Save failed: {str(e)}")
#    output.to_csv(str(Path.cwd()/"output"/"output.csv"), index=False)  # py交互环境
if __name__ == "__main__":
    main()