"""Flask + pandas + LLM data analysis teaching demo.
Flask + pandas + 大模型数据分析教学示例。

请求链路：上传 CSV -> 清洗并聚合 -> 生成图表 -> 将脱敏摘要发给模型。
原始 CSV 不写入磁盘，图表以内嵌 base64 图片返回浏览器。
"""

from __future__ import annotations

import base64
import io
import json
import logging
import os
import re
import urllib.error
import urllib.request
# Use a non-interactive backend because charts are rendered on the server.
# 使用非交互式后端，因为图表由服务器生成。
# They are returned in the page instead of opening a desktop window.
# 图表会返回到网页中，不会在桌面窗口打开。
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
from dotenv import load_dotenv
from flask import Flask, jsonify, render_template, request

# Load local development settings from .env.
# 从 .env 加载本地开发配置。
# Production can set the same variables through its process or container.
# 生产环境也可通过进程或容器变量传入相同配置。
load_dotenv()

# Keep upload and analysis limits together for easy classroom adjustment.
# 将上传和分析限制集中定义，便于课堂调整。
ROOT = os.path.dirname(os.path.abspath(__file__))
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024
app.logger.setLevel(logging.INFO)

# These columns define the sales dataset accepted by this demo.
# 这些字段定义了本示例支持的销售数据格式。
REQUIRED_COLUMNS = {"date", "category", "amount", "quantity"}
MAX_ROWS = 20_000
MAX_CATEGORIES = 12


class DataError(ValueError):
    """A user-correctable CSV or validation error
    可由用户修正的 CSV 或数据校验错误。
    """


def read_csv_upload(file_bytes: bytes) -> pd.DataFrame:
    """Read request bytes and validate size, encoding, and schema
    读取请求字节并校验文件大小、编码和字段结构。
    """
    if not file_bytes:
        raise DataError("CSV 文件为空，请选择包含数据行的文件。")

    frame = None
    last_error = None
    # Try common classroom encodings.
    # 依次尝试课堂中常见的文件编码。
    # utf-8-sig also removes a UTF-8 BOM.
    # utf-8-sig 还会自动移除 UTF-8 文件开头的 BOM 标记。
    for encoding in ("utf-8-sig", "gbk"):
        try:
            frame = pd.read_csv(io.BytesIO(file_bytes), encoding=encoding)
            break
        except UnicodeDecodeError as exc:
            last_error = exc
        except pd.errors.EmptyDataError as exc:
            raise DataError("CSV 文件没有可读取的表头或数据。") from exc
        except pd.errors.ParserError as exc:
            raise DataError("CSV 格式无法解析，请检查分隔符和引号。") from exc
    if frame is None:
        raise DataError("无法识别 CSV 编码，请另存为 UTF-8 或 GBK 编码。") from last_error
    if frame.empty:
        raise DataError("CSV 中没有数据行。")
    if len(frame) > MAX_ROWS:
        raise DataError(f"演示版最多分析 {MAX_ROWS:,} 行，请缩小文件后重试。")

    # Normalize names so Date and DATE match the schema.
    # 统一列名格式，使 Date、DATE 都能匹配必需字段。
    frame.columns = [str(column).strip().lower() for column in frame.columns]
    missing_columns = sorted(REQUIRED_COLUMNS - set(frame.columns))
    if missing_columns:
        raise DataError("缺少必要列：" + ", ".join(missing_columns))

    return frame


def make_analysis(frame: pd.DataFrame) -> tuple[pd.DataFrame, dict]:
    """Clean required fields and calculate chart/UI metrics
    清洗必需字段，并计算图表和页面所需指标。
    """
    raw_rows = len(frame)
    # Capture missing counts before dropping invalid rows.
    # 删除无效行前先统计各列缺失值，供报告展示。
    missing_before = {str(k): int(v) for k, v in frame.isna().sum().items()}
    clean = frame.copy()

    # Convert text columns to types needed for grouping and arithmetic.
    # 将文本列转换为分组和计算所需的数据类型。
    clean["date"] = pd.to_datetime(clean["date"], errors="coerce")
    clean["amount"] = pd.to_numeric(clean["amount"], errors="coerce")
    clean["quantity"] = pd.to_numeric(clean["quantity"], errors="coerce")
    clean["category"] = clean["category"].astype("string").str.strip()
    # Remove records with invalid required values or impossible sales amounts.
    # 移除必需字段无效或金额、数量不合理的记录。
    clean = clean.dropna(subset=list(REQUIRED_COLUMNS))
    clean = clean[(clean["amount"] >= 0) & (clean["quantity"] > 0)]
    clean = clean[clean["category"] != ""]
    if clean.empty:
        raise DataError("清洗后没有可分析记录，请检查日期、类别、金额和数量。")

    # Add a month key and aggregate values for the charts.
    # 添加月份字段，并汇总生成分类图和趋势图的数据。
    clean["month"] = clean["date"].dt.to_period("M").astype(str)
    by_category = (
        clean.groupby("category", as_index=False)[["amount", "quantity"]]
        .sum()
        .sort_values("amount", ascending=False)
    )
    by_month = clean.groupby("month")["amount"].sum().sort_index()
    describe = clean["amount"].describe()
    # Convert NumPy/pandas scalars to plain Python values for JSON.
    # 将 NumPy、pandas 标量转换为普通 Python 类型以便 JSON 序列化。
    summary = {
        "source_rows": int(raw_rows),
        "rows": int(len(clean)),
        "dropped_rows": int(raw_rows - len(clean)),
        "missing_by_column": missing_before,
        "columns": [str(column) for column in frame.columns],
        "date_range": [clean["date"].min().strftime("%Y-%m-%d"), clean["date"].max().strftime("%Y-%m-%d")],
        "total_sales": round(float(clean["amount"].sum()), 2),
        "total_quantity": round(float(clean["quantity"].sum()), 2),
        "average_order_amount": round(float(clean["amount"].mean()), 2),
        "amount_describe": {key: round(float(value), 2) for key, value in describe.items()},
        "sales_by_category": [
            {"category": str(row.category), "amount": round(float(row.amount), 2), "quantity": round(float(row.quantity), 2)}
            for row in by_category.head(MAX_CATEGORIES).itertuples(index=False)
        ],
        "sales_by_month": {str(month): round(float(amount), 2) for month, amount in by_month.items()},
    }
    return clean, summary


def chart_data_uri(frame: pd.DataFrame, summary: dict) -> dict:
    """Render aggregate charts in memory as browser-ready data URIs
    在内存中生成汇总图表，并转为浏览器可用的数据 URI。
    """
    # Agg works without a desktop; uploaded rows and charts are not saved.
    # Agg 后端无需桌面环境；不会保存上传明细或图表文件。
    plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial", "DejaVu Sans"]
    plt.rcParams["axes.unicode_minus"] = False
    charts = {}
    category = pd.DataFrame(summary["sales_by_category"])
    # Use labels and values from the aggregated summary only.
    # 图表标签和数值仅取自已汇总的数据。
    for key, title, color, labels, values, ylabel in (
        ("category", "Sales by Category", "#4778f5", category.get("category", []), category.get("amount", []), "Sales amount"),
        ("monthly", "Monthly Sales Trend", "#10a98a", list(summary["sales_by_month"].keys()), list(summary["sales_by_month"].values()), "Sales amount"),
    ):
        fig, ax = plt.subplots(figsize=(8, 4.2), dpi=130)
        if key == "category":
            ax.bar(labels, values, color=color, width=0.62)
            ax.tick_params(axis="x", rotation=25)
        else:
            ax.plot(labels, values, color=color, marker="o", linewidth=2.5)
            ax.tick_params(axis="x", rotation=25)
        ax.set_title(title, loc="left", fontsize=13, pad=14, color="#172033")
        ax.set_ylabel(ylabel, color="#667085")
        ax.grid(axis="y", alpha=0.2)
        ax.spines[["top", "right"]].set_visible(False)
        fig.tight_layout()
        output = io.BytesIO()
        fig.savefig(output, format="png", bbox_inches="tight", facecolor="white")
        plt.close(fig)
        encoded = base64.b64encode(output.getvalue()).decode("ascii")
        charts[key] = "data:image/png;base64," + encoded
    return charts


def anonymized_model_summary(summary: dict) -> dict:
    """Build a minimal payload and hide original category labels
    生成最小化摘要，并隐藏原始类别名称。
    """
    # Category labels may contain sensitive text; replace them before sending.
    # 类别名称可能包含敏感文本，发送前先替换为匿名标签。
    return {
        "rows_analyzed": summary["rows"],
        "rows_excluded_during_cleaning": summary["dropped_rows"],
        "date_range": summary["date_range"],
        "total_sales": summary["total_sales"],
        "total_quantity": summary["total_quantity"],
        "average_order_amount": summary["average_order_amount"],
        "amount_statistics": summary["amount_describe"],
        "sales_by_category": [
            {"category": f"类别{index + 1}", "sales": row["amount"], "quantity": row["quantity"]}
            for index, row in enumerate(summary["sales_by_category"])
        ],
        "sales_by_month": summary["sales_by_month"],
        "missing_values_by_required_field": {key: value for key, value in summary["missing_by_column"].items() if key in REQUIRED_COLUMNS},
    }


def parse_json_object(content: str) -> dict:
    """Parse model JSON, including code-fenced responses
    解析模型返回的 JSON，也兼容带代码围栏的响应。
    """
    text = content.strip()
    text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.IGNORECASE)
    result = json.loads(text)
    if not isinstance(result, dict):
        raise ValueError("模型返回的不是 JSON 对象")
    return result


def request_ai_insight(summary: dict) -> dict:
    """Call a compatible chat endpoint; local analysis works without a key
    调用兼容的对话接口；未配置密钥时本地统计仍可使用。
    """
    api_key = os.getenv("MIMO_API_KEY") or os.getenv("OPENAI_API_KEY")
    if not api_key:
        return {"available": False, "message": "尚未配置模型密钥。统计和图表已完成；配置 MIMO_API_KEY 后可生成 AI 洞察。"}

    base_url = os.getenv("MIMO_BASE_URL", "https://api.xiaomimimo.com/v1").rstrip("/")
    model = os.getenv("MIMO_MODEL", "mimo-v2.6-flash")
    # Request a stable JSON shape for the three report cards.
    # 要求模型返回固定 JSON 结构，供页面生成三类报告卡片。
    payload = {
        "model": model,
        "temperature": 0.2,
        "response_format": {"type": "json_object"},
        "messages": [
            {"role": "system", "content": "你是审慎的数据分析助理。只根据给定的聚合统计数字作答，不推断因果，不编造字段、背景或数据。请输出 JSON 对象，且必须有 facts、risks、actions 三个键，每个键对应 2 至 4 条简短中文字符串。报告用于人工参考，不构成自动业务决策。"},
            {"role": "user", "content": "请分析以下脱敏聚合摘要。facts 写可从数据直接核对的事实；risks 写数据质量或解读限制；actions 写需人工评估的低风险建议。摘要：\n" + json.dumps(anonymized_model_summary(summary), ensure_ascii=False)},
        ],
    }
    # Keep the API key in this server-side request; never expose it to the page.
    # 密钥只用于服务端请求，绝不传给网页。
    request = urllib.request.Request(
        base_url + "/chat/completions",
        data=json.dumps(payload).encode("utf-8"),
        headers={"Authorization": "Bearer " + api_key, "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=25) as response:
            response_body = json.loads(response.read().decode("utf-8"))
        content = response_body["choices"][0]["message"]["content"]
        insight = parse_json_object(content)
        # Validate report lists and limit text length before returning.
        # 返回前校验报告字段，并限制每条文本长度。
        for key in ("facts", "risks", "actions"):
            if not isinstance(insight.get(key), list):
                raise ValueError("模型报告缺少必需字段")
            insight[key] = [str(item)[:500] for item in insight[key][:6]]
        return {"available": True, "report": insight, "model": model}
    except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError, KeyError, IndexError, TypeError, ValueError, json.JSONDecodeError) as exc:
        app.logger.warning("LLM insight request failed (%s)", type(exc).__name__)
        return {"available": False, "message": "模型暂时无法生成报告，请检查服务配置后重试。统计与图表仍可使用。"}


@app.get("/")
def index():
    """Serve the upload and results page
    返回上传和分析结果页面。
    """
    return render_template("index.html")


@app.get("/sample.csv")
def sample_csv():
    """Serve the bundled sample CSV
    返回静态目录中内置的示例 CSV 文件。
    """
    return app.send_static_file("sample_sales.csv")


@app.get("/api/health")
def health():
    """Report whether a model API key is configured
    返回是否已配置大模型 API 密钥。
    """
    return jsonify({"ok": True, "llm_configured": bool(os.getenv("MIMO_API_KEY") or os.getenv("OPENAI_API_KEY"))})


@app.post("/api/analyze")
def analyze():
    """Validate and analyze one upload, then return metrics, charts, and insight
    校验并分析上传文件，返回指标、图表和 AI 洞察。
    """
    upload = request.files.get("file")
    if upload is None or not upload.filename:
        return jsonify({"message": "请选择一个 CSV 文件。"}), 400
    if "." not in upload.filename or upload.filename.rsplit(".", 1)[1].lower() != "csv":
        return jsonify({"message": "只支持 CSV 文件。"}), 400
    try:
        # Read the upload into memory without explicitly saving an original copy.
        # 在内存中读取上传文件，不主动保存原始文件副本。
        frame = read_csv_upload(upload.read())
        clean, summary = make_analysis(frame)
        charts = chart_data_uri(clean, summary)
        insight = request_ai_insight(summary)
        return jsonify({"summary": summary, "charts": charts, "insight": insight})
    except DataError as exc:
        return jsonify({"message": str(exc)}), 400
    # Log details server-side and return a safe message.
    # 详细错误只写入服务端日志，并向用户返回安全提示。
    except Exception as exc:
        app.logger.exception("Analysis failed (%s)", type(exc).__name__)
        return jsonify({"message": "分析失败，请检查 CSV 内容后重试。"}), 500


@app.errorhandler(413)
def too_large(_error):
    """Format Flask's request-size error as JSON
    将 Flask 的请求大小错误转换为页面使用的 JSON 格式。
    """
    return jsonify({"message": "文件不能超过 2 MB。"}), 413


if __name__ == "__main__":
    # Debug mode is opt-in; bind to localhost for the classroom demo.
    # 调试模式需显式开启；课堂示例默认只监听本机。
    app.run(host="127.0.0.1", port=int(os.getenv("PORT", "5006")), debug=os.getenv("FLASK_DEBUG") == "1")
