"""Point-count correction must withdraw old drafts without destroying saves."""
from pathlib import Path
from types import SimpleNamespace
import json

import pytest

from pallet import mask_model_review as review
from pallet.mask_gallery_review import ReviewError


def handler(path,command='GET'):
    h=object.__new__(review.ModelMaskHandler);h.path=path;h.command=command;h.server=SimpleNamespace(gallery=SimpleNamespace(count=588))
    h.json=lambda value:value
    h.respond=lambda status,raw,mime:dict(status=status,text=raw.decode(),mime=mime)
    return h


@pytest.fixture
def pause(tmp_path,monkeypatch):
    p=tmp_path/'pause.json';monkeypatch.setattr(review,'KEYPOINT_PAUSE',p)
    p.write_text(json.dumps(dict(active=True,reason_zh='按所属类别关键点数量重新生成')))
    return p


def test_health_does_not_misreport588_available(pause):
    health=handler('/healthz').route()
    assert health['targets']==588 and health['active_draft_targets']==0
    assert health['keypoint_alignment_paused'] and not health['editing_enabled']


def test_original_url_shows_safe_notice_not_dense_drafts(pause):
    response=handler('/').route()
    assert response['status']==200 and '已暂停' in response['text'] and '未清除本机草稿' in response['text']
    assert '<article' not in response['text']


@pytest.mark.parametrize('path,command',[('/api/review/targets/'+'a'*24,'GET'),('/api/review/annotations/'+'a'*24,'POST'),
    ('/labelme/a.json','GET'),('/masks/a.png','GET'),('/cases/a.png','GET'),('/%63ases/a.png','GET')])
def test_old_draft_cannot_be_loaded_exported_or_saved_during_hold(pause,path,command):
    with pytest.raises(ReviewError) as error:handler(path,command).route()
    assert error.value.status==503 and '草稿保留' in error.value.message


def test_corrupt_control_fails_closed(pause):
    pause.write_text('broken');assert review.keypoint_pause()['active']


def test_unheld_health_preserves_original_contract(pause):
    pause.unlink();health=handler('/healthz').route()
    assert health['editing_enabled'] and health['active_draft_targets']==588
