"""ローカル復習サーバ (Flask)。待受は 127.0.0.1 のみ。外部サービスへの送信なし。
起動: python3 app/server.py   → http://127.0.0.1:8765/
"""
from __future__ import annotations
import sys, json, datetime, html, re
from pathlib import Path
from flask import Flask, jsonify, request, send_from_directory, render_template, abort, Response

APP_DIR = Path(__file__).resolve().parent
ROOT = APP_DIR.parent
sys.path.insert(0, str(APP_DIR))
from study_db import StudyDB
from scheduler import next_state, build_queue, RESULTS

def card_id(problem_id: str, n: int = 1) -> str:
    """scripts/common.card_id と同じ形式 (学校接頭辞を含む問題ID + 連番)。"""
    return "CARD-" + problem_id + f"-{n:02d}"

CONFIG = json.loads((ROOT / "config" / "settings.json").read_text(encoding="utf-8"))
app = Flask(__name__, template_folder=str(APP_DIR / "templates"), static_folder=str(APP_DIR / "static"))
app.config["JSON_AS_ASCII"] = False
db = StudyDB(ROOT / "db" / "study.sqlite")

_cat = {"mtime": None, "data": None}
def catalog():
    p = ROOT / "data" / "catalog.json"
    m = p.stat().st_mtime
    if _cat["mtime"] != m:
        d = json.loads(p.read_text(encoding="utf-8"))
        d["by_id"] = {q["problem_id"]: q for q in d["problems"]}
        d["exam_by_id"] = {e["exam_id"]: e for e in d["exams"]}
        _cat.update(mtime=m, data=d)
    return _cat["data"]

def now():
    return datetime.datetime.now().astimezone()

def is_student_visible(p, unlocked, suspended):
    return p["kind"] == "sub" and p["status"]["publish"] == "publishable" and p["exam_id"] in unlocked \
        and p["problem_id"] not in suspended and not p["status"].get("suspended")

def card_view(p, hide_tags=True):
    """生徒向け表面/裏面データ。表面には答え・分野タグを含めない。"""
    front = {
        "problem_id": p["problem_id"], "display": p["display"], "exam_id": p["exam_id"], "parent_id": p["parent_id"],
        "number": p["number"], "content_version": p["content_version"],
        "images": [{"role": r["role"], "src": "/assets/" + r["image_path"].replace("assets/", "", 1), "note": r.get("note"), "page": r["page_display"]}
                   for r in p["source_refs"]],
        "depends_on": p.get("depends_on", []),
        "given_results": [{"problem_id": d["problem_id"], "label": d.get("label")} for d in p.get("depends_on", [])],
        "est_minutes": (p.get("learning") or {}).get("est_minutes"),
    }
    sol = p.get("solution") or {}
    back = {
        "answer": sol.get("final_answer"), "official_answer": (p.get("official_answer") or {}).get("raw"),
        "official_label": (p.get("official_answer") or {}).get("label", "学校公表の正解"), "school": p.get("school"),
        "first_insight": sol.get("first_insight"), "insight_basis": sol.get("insight_basis"),
        "steps": sol.get("steps", []), "why": sol.get("why"), "check": sol.get("check"),
        "common_errors": sol.get("common_errors", []), "minimal_points": sol.get("minimal_points", []),
        "related": sol.get("related", []),
        "teacher": p.get("teacher"), "analysis": p.get("analysis"), "learning": p.get("learning"),
        "hints": p.get("hints") or [], "verification": p.get("verification"),
        "references": p.get("references"), "source_refs": p["source_refs"],
        "status": p["status"], "publish_checks": p.get("publish_checks"),
    }
    return {"front": front, "back": back}

# ---------- pages
@app.route("/")
def index():
    return render_template("index.html")

@app.route("/assets/<path:path>")
def assets(path):
    return send_from_directory(ROOT / "assets", path)

# ---------- api
@app.route("/api/overview")
def api_overview():
    c = catalog(); unlocked = db.unlocked(); susp = db.suspended_pids(); states = db.all_states()
    exams = []
    for e in c["exams"]:
        subs = [p for p in c["problems"] if p["kind"] == "sub" and p["exam_id"] == e["exam_id"]]
        pub = [p for p in subs if p["status"]["publish"] == "publishable"]
        exams.append({"exam_id": e["exam_id"], "display_name": e["display_name"], "year": e["year"], "round": e["round"], "school_code": e.get("school_code", "TOYO"), "school": e.get("school"),
                      "n_subs": len(subs), "n_publishable": len(pub), "unlocked": e["exam_id"] in unlocked,
                      "n_reviewed": sum(1 for p in subs if p["problem_id"] in states)})
    due = 0; weak = 0
    for pid, st in states.items():
        p = c["by_id"].get(pid)
        if not p or not is_student_visible(p, unlocked, susp): continue
        if st.get("due_at") and st["due_at"] <= now().isoformat(): due += 1
        if st.get("learning_state") in ("lapsed", "read_only", "hinted", "slow_correct"): weak += 1
    return jsonify({"exams": exams, "counts": c["counts"], "due": due, "weak": weak,
                    "settings": {"daily_time_limit_minutes": db.get_setting("daily_time_limit_minutes", CONFIG["review"]["daily_time_limit_minutes"]),
                                 "new_cards_per_day": db.get_setting("new_cards_per_day", CONFIG["review"]["default_new_cards_per_day"])},
                    "open_reports": len(db.open_reports())})

@app.route("/api/settings", methods=["POST"])
def api_settings():
    d = request.get_json(force=True)
    for k in ("daily_time_limit_minutes", "new_cards_per_day"):
        if k in d: db.set_setting(k, d[k])
    return jsonify({"ok": True})

@app.route("/api/unlock", methods=["POST"])
def api_unlock():
    d = request.get_json(force=True)
    db.set_unlocked(d["exam_id"], bool(d["unlocked"]))
    return jsonify({"ok": True})

def vocab(c):
    fields, cores, prereqs, diffs = set(), set(), set(), set()
    for p in c["problems"]:
        a = p.get("analysis") or {}
        if a.get("primary_field"): fields.add(a["primary_field"])
        fields.update(a.get("secondary_fields", [])); cores.update(a.get("cores_canonical", []))
        prereqs.update(a.get("prereq_canonical", []))
        if (p.get("learning") or {}).get("difficulty"): diffs.add(p["learning"]["difficulty"])
    return {"fields": sorted(fields), "cores": sorted(cores), "prerequisites": sorted(x for x in prereqs if x), "difficulties": sorted(diffs)}

@app.route("/api/search")
def api_search():
    c = catalog(); unlocked = db.unlocked(); susp = db.suspended_pids(); states = db.all_states()
    q = request.args
    admin = q.get("admin") == "1"
    out = []
    for p in c["problems"]:
        if p["kind"] != "sub": continue
        vis = is_student_visible(p, unlocked, susp)
        if not admin and not vis: continue
        a = p.get("analysis") or {}; le = p.get("learning") or {}
        if q.get("school") and p.get("school_code", "TOYO") != q["school"]: continue
        if q.get("year") and str(p["year"]) != q["year"]: continue
        if q.get("round") and str(p["round"]) != q["round"]: continue
        if q.get("field") and q["field"] not in [a.get("primary_field")] + a.get("secondary_fields", []): continue
        if q.get("core") and q["core"] not in a.get("cores_canonical", []) + a.get("cores", []): continue
        if q.get("prereq") and q["prereq"] not in a.get("prereq_canonical", []): continue
        if q.get("difficulty") and le.get("difficulty") != q["difficulty"]: continue
        st = states.get(p["problem_id"])
        ls = (st or {}).get("learning_state") or "new"
        if q.get("state") and q["state"] != ls: continue
        if q.get("text"):
            blob = json.dumps({k: p.get(k) for k in ("display", "transcript_confirmed", "analysis", "solution")}, ensure_ascii=False)
            if q["text"] not in blob: continue
        out.append({"problem_id": p["problem_id"], "display": p["display"], "year": p["year"], "round": p["round"], "school_code": p.get("school_code", "TOYO"),
                    "primary_field": a.get("primary_field"), "cores": a.get("cores_canonical", []), "cores_raw": a.get("cores", []), "difficulty": le.get("difficulty"),
                    "est_minutes": le.get("est_minutes"), "learning_state": ls, "due_at": (st or {}).get("due_at"),
                    "publish": p["status"]["publish"], "hold_reasons": p["status"]["hold_reasons"], "visible": vis,
                    "thumb": "/assets/" + p["source_refs"][-1]["image_path"].replace("assets/", "", 1) if p["source_refs"] else None})
    return jsonify({"items": out, "vocab": vocab(c)})

@app.route("/api/card/<pid>")
def api_card(pid):
    c = catalog(); p = c["by_id"].get(pid)
    if not p or p["kind"] != "sub": abort(404)
    admin = request.args.get("admin") == "1"
    if not admin and not is_student_visible(p, db.unlocked(), db.suspended_pids()): abort(403)
    v = card_view(p)
    v["state"] = dict(db.get_state(pid) or {}) ; v["history"] = db.reviews_for(pid, 20)
    # 兄弟 (同じ大問) の一覧 (原順序演習用)
    v["siblings"] = c["by_id"][p["parent_id"]]["sub_ids"] if p.get("parent_id") else []
    return jsonify(v)

@app.route("/api/queue")
def api_queue():
    c = catalog(); unlocked = db.unlocked(); susp = db.suspended_pids(); states = db.all_states()
    cards = []
    for p in c["problems"]:
        if not is_student_visible(p, unlocked, susp): continue
        le = p.get("learning") or {}
        cards.append({"problem_id": p["problem_id"], "parent_id": p["parent_id"], "order_index": p["order_index"],
                      "est_minutes": le.get("est_minutes") or 5, "prereq_weight": le.get("prereq_weight", 0), "display": p["display"]})
    mode = request.args.get("mode", "review")
    if mode == "wrong":
        cards = [cd for cd in cards if (states.get(cd["problem_id"]) or {}).get("learning_state") in ("lapsed", "read_only", "hinted", "slow_correct")]
    tl = db.get_setting("daily_time_limit_minutes", CONFIG["review"]["daily_time_limit_minutes"])
    npd = db.get_setting("new_cards_per_day", CONFIG["review"]["default_new_cards_per_day"])
    qd = build_queue(cards, states, CONFIG["review"], now(), time_limit_min=tl if mode == "review" else None, new_per_day=npd if mode == "review" else 0)
    return jsonify({"queue": [{"problem_id": cd["problem_id"], "display": cd["display"], "state": (states.get(cd["problem_id"]) or {}).get("learning_state", "new")} for cd in qd]})

@app.route("/api/exam/<eid>/sequence")
def api_exam_sequence(eid):
    """試験単位の原順序演習: 公開可能かつ解禁済みの小問を紙面順に返す。未公開は理由付きで飛ばす。"""
    c = catalog(); unlocked = db.unlocked(); susp = db.suspended_pids()
    if eid not in unlocked and request.args.get("admin") != "1": abort(403)
    seq = []
    for p in c["problems"]:
        if p["kind"] != "sub" or p["exam_id"] != eid: continue
        seq.append({"problem_id": p["problem_id"], "display": p["display"], "available": is_student_visible(p, unlocked, susp) or (request.args.get("admin") == "1" and p["status"]["publish"] == "publishable"),
                    "hold_reasons": p["status"]["hold_reasons"]})
    return jsonify({"exam": c["exam_by_id"][eid], "sequence": seq})

@app.route("/api/review", methods=["POST"])
def api_review():
    d = request.get_json(force=True)
    c = catalog(); p = c["by_id"].get(d["problem_id"])
    if not p: abort(404)
    if d["result"] not in RESULTS: abort(400)
    prev = db.get_state(p["problem_id"])
    st = next_state(dict(prev) if prev else None, d["result"], d.get("hints_used") or [], d.get("seconds"),
                    (p.get("learning") or {}).get("est_minutes"), CONFIG["review"], now())
    st["content_version"] = p["content_version"]
    cid = d.get("card_id") or card_id(p["problem_id"])   # common.card_id と同じ形式 (学校接頭辞を含む)
    db.add_review(problem_id=p["problem_id"], card_id=cid, content_version=p["content_version"], mode=d.get("mode", "review"),
                  result=d["result"], hints_used=d.get("hints_used") or [], error_tags=d.get("error_tags") or [],
                  seconds=d.get("seconds"), paused_seconds=d.get("paused_seconds"), note=d.get("note"))
    db.set_state(p["problem_id"], **st)
    return jsonify({"ok": True, "state": st})

@app.route("/api/history")
def api_history():
    c = catalog()
    rows = db.recent_reviews(300)
    for r in rows:
        p = c["by_id"].get(r["problem_id"]); r["display"] = p["display"] if p else r["problem_id"]
    return jsonify({"reviews": rows, "states": db.all_states(), "exam_sessions": db.exam_sessions()})

@app.route("/api/report", methods=["POST"])
def api_report():
    d = request.get_json(force=True)
    db.add_report(d["problem_id"], d.get("content_version"), d.get("text", ""))
    return jsonify({"ok": True})

@app.route("/api/admin/pending")
def api_pending():
    c = catalog()
    items = [{"problem_id": p["problem_id"], "display": p["display"], "hold_reasons": p["status"]["hold_reasons"], "answer_status": p["status"]["answer"],
              "extraction": p["status"]["extraction"], "checks": p.get("publish_checks")} for p in c["problems"] if p["kind"] == "sub" and p["status"]["publish"] != "publishable"]
    return jsonify({"pending": items, "reports": db.open_reports()})

@app.route("/api/admin/report/<int:rid>/resolve", methods=["POST"])
def api_resolve(rid):
    db.resolve_report(rid); return jsonify({"ok": True})

@app.route("/api/exam_session", methods=["POST"])
def api_exam_session():
    d = request.get_json(force=True)
    db.add_exam_session(d["exam_id"], d.get("results", {})); return jsonify({"ok": True})

@app.route("/api/print")
def api_print():
    """印刷用: 指定ID (カンマ区切り) または誤答問題の問題面/解答面を返す。"""
    c = catalog(); unlocked = db.unlocked(); susp = db.suspended_pids(); states = db.all_states()
    ids = [x for x in request.args.get("ids", "").split(",") if x]
    if request.args.get("wrong") == "1":
        ids = [pid for pid, st in states.items() if st.get("learning_state") in ("lapsed", "read_only", "hinted", "slow_correct")]
    admin = request.args.get("admin") == "1"
    cards = []
    for pid in ids:
        p = c["by_id"].get(pid)
        if not p: continue
        if not admin and not is_student_visible(p, unlocked, susp): continue
        cards.append(card_view(p))
    return jsonify({"cards": cards})

@app.route("/print")
def print_page():
    return render_template("print.html")

if __name__ == "__main__":
    host = CONFIG["server"]["host"]; port = int(CONFIG["server"]["port"])
    print(f"復習画面: http://{host}:{port}/   (localhost のみ)")
    app.run(host=host, port=port, debug=False)
