"""学習履歴の保存・スケジューラ・未見保持の除外・問題変更時の再検証・書き出しと再取込み (アプリを実際に呼ぶ)。"""
import json, datetime, importlib, shutil, sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]

@pytest.fixture
def client(tmp_path, monkeypatch):
    sys.path.insert(0, str(ROOT / "app"))
    import server
    importlib.reload(server)
    from study_db import StudyDB
    server.db = StudyDB(tmp_path / "study.sqlite")   # 本物の履歴DBには触れない
    server.app.config["TESTING"] = True
    return server.app.test_client(), server

def first_publishable(server):
    c = server.catalog()
    for p in c["problems"]:
        if p["kind"] == "sub" and p["status"]["publish"] == "publishable": return p
    pytest.skip("公開可能な小問が無い")

def test_locked_exam_is_hidden_everywhere(client):
    cl, server = client
    p = first_publishable(server)
    assert cl.get(f"/api/card/{p['problem_id']}").status_code == 403
    assert all(i["problem_id"] != p["problem_id"] for i in cl.get("/api/search").get_json()["items"])
    assert cl.get("/api/queue").get_json()["queue"] == []
    assert cl.get(f"/api/exam/{p['exam_id']}/sequence").status_code == 403
    assert cl.get(f"/api/print?ids={p['problem_id']}").get_json()["cards"] == []

def test_unlock_review_and_history(client):
    cl, server = client
    p = first_publishable(server)
    assert cl.post("/api/unlock", json={"exam_id": p["exam_id"], "unlocked": True}).get_json()["ok"]
    card = cl.get(f"/api/card/{p['problem_id']}").get_json()
    assert card["front"]["images"] and "answer" not in json.dumps(card["front"], ensure_ascii=False)
    ans = str(card["back"]["answer"])
    from common import answer_leaks
    front_text = " ".join([card["front"]["display"]] + [im.get("note") or "" for im in card["front"]["images"]])
    assert ans and not answer_leaks(ans, front_text)
    # 画像は region_id 名のみ (答えを含む名前やaltが無い)
    assert all(im["src"].endswith(".png") and "/assets/crops/" in im["src"] for im in card["front"]["images"])
    q = cl.get("/api/queue").get_json()["queue"]; assert any(x["problem_id"] == p["problem_id"] for x in q)
    r = cl.post("/api/review", json={"problem_id": p["problem_id"], "result": "incorrect", "hints_used": [1], "error_tags": ["計算ミス"], "seconds": 120}).get_json()
    assert r["state"]["learning_state"] == "lapsed" and r["state"]["lapses"] == 1
    h = cl.get("/api/history").get_json(); assert h["reviews"][0]["problem_id"] == p["problem_id"]
    assert any(x["problem_id"] == p["problem_id"] for x in cl.get("/api/queue?mode=wrong").get_json()["queue"])
    r2 = cl.post("/api/review", json={"problem_id": p["problem_id"], "result": "correct_self", "hints_used": [], "seconds": 60}).get_json()
    assert r2["state"]["interval_index"] == 1 and "次回" in r2["state"]["explain"]
    # 試験単位の原順序
    seq = cl.get(f"/api/exam/{p['exam_id']}/sequence").get_json()["sequence"]; assert seq and seq[0]["problem_id"].endswith("-Q01-S01")

def test_report_suspends_card(client):
    cl, server = client
    p = first_publishable(server)
    cl.post("/api/unlock", json={"exam_id": p["exam_id"], "unlocked": True})
    cl.post("/api/report", json={"problem_id": p["problem_id"], "content_version": 1, "text": "図が欠けている"})
    assert cl.get(f"/api/card/{p['problem_id']}").status_code == 403
    pend = cl.get("/api/admin/pending").get_json(); assert pend["reports"][0]["problem_id"] == p["problem_id"]

def test_scheduler_explainable_and_sibling_spacing():
    sys.path.insert(0, str(ROOT / "app"))
    from scheduler import next_state, build_queue
    cfg = {"intervals_days": [1, 3, 7], "lapse_interval_days": 1, "sibling_spacing_min_cards": 2, "default_new_cards_per_day": 10}
    now = datetime.datetime(2026, 1, 1, 9, 0)
    st = next_state(None, "correct_self", [], 100, 5, cfg, now); assert st["interval_index"] == 1 and st["due_at"].startswith("2026-01-04")
    st2 = next_state(st, "correct_with_hint", [2], 100, 5, cfg, now); assert st2["interval_index"] == 1 and st2["learning_state"] == "hinted"
    st3 = next_state(st2, "incorrect", [], 100, 5, cfg, now); assert st3["interval_index"] == 0 and st3["lapses"] == 1
    st4 = next_state(None, "correct_self", [], 5 * 60 * 3, 5, cfg, now); assert st4["learning_state"] == "slow_correct"
    cards = [{"problem_id": f"P{i}", "parent_id": "A" if i < 3 else "B", "est_minutes": 1, "order_index": i} for i in range(6)]
    q = build_queue(cards, {}, cfg, now)
    assert [c["parent_id"] for c in q[:4]] == ["A", "B", "A", "B"]
    q2 = build_queue(cards, {}, cfg, now, time_limit_min=3); assert len(q2) == 3

def test_content_change_invalidates_verification(tmp_path):
    sys.path.insert(0, str(ROOT / "scripts"))
    from build_problems import sig
    rec = {"transcript": {"text": "a"}, "solution": {"final_answer": "1"}}
    s1 = sig(rec); rec["solution"]["final_answer"] = "2"; assert sig(rec) != s1

def test_export_and_reimport(client, tmp_path, monkeypatch):
    cl, server = client
    p = first_publishable(server)
    import subprocess
    # 一時的な履歴DBでは解禁情報が無いので export は0件になる → 本番DBを使わず、export が壊れないことと再取込み形式を確認
    r = subprocess.run([sys.executable, str(ROOT / "scripts" / "export.py")], capture_output=True, text=True, cwd=ROOT / "scripts")
    assert r.returncode == 0, r.stderr
    chk = json.loads((ROOT / "exports" / "reimport_check.json").read_text(encoding="utf-8")); assert chk["ok"]
    d = json.loads((ROOT / "exports" / "cards.json").read_text(encoding="utf-8"))
    for c in d["cards"]:
        for im in c["front"]["images"]: assert (ROOT / "exports" / im["file"]).exists()
