"""Cleanup is narrow, reversible and refuses changed or human-owned records."""
import hashlib
import importlib.util
import json
from pathlib import Path
import sqlite3

import numpy as np
import pytest

SCRIPT = Path(__file__).resolve().parents[1]/'scripts/cleanup_legacy_review_intermediates.py'
SPEC = importlib.util.spec_from_file_location('cleanup_legacy_review_intermediates', SCRIPT)
cleanup = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(cleanup)


@pytest.mark.parametrize('path', [
    'outputs/pallet_pose_human_review_v1/geometry/a.npz',
    'outputs/pallet_dataset_formal_v1/dataset/a.npz',
    'outputs/review_round_001/labels/a.jsonl',
    'outputs/review_round_001/reviews/a.json',
    'outputs/review_round_001/tasks/a.json',
    'outputs/review_round_001/cache/source.pcd',
    'outputs/review_round_001/views/'+'a'*20+'/manual.png',
    'outputs/review_round_001/views/'+'a'*20+'/original.png',
    'outputs/review_round_001/last.pt',
    'outputs/recipe_rf_cli_smoke_v5_gpu1/best.pt',
    'outputs/review_round_001/delivery.zip',
    'outputs/pallet_pose_review_validation_v14/reviews_before_v14.sqlite3',
])
def test_human_records_formal_sources_models_and_delivery_archives_are_not_targets(path):
    assert not cleanup.eligible_target(path)


def test_exactly_scoped_cache_and_three_rendered_view_names_are_allowed():
    assert cleanup.eligible_target('outputs/review_round_001/cache/a.npz')
    assert cleanup.eligible_target('outputs/full_review_val_002_v5/views/'+'a'*20+'/intensity.png')
    assert cleanup.eligible_target('outputs/audit_review_round_003_small/views/'+'a'*20+'/depth.png')
    assert not cleanup.eligible_target('outputs/review_round_001/views/arbitrary/intensity.png')


@pytest.fixture
def environment(tmp_path, monkeypatch):
    monkeypatch.setattr(cleanup, 'PROJECT', tmp_path)
    (tmp_path/'configs').mkdir()
    (tmp_path/'configs/active_dataset.json').write_text('{"preserve":true}')
    formal = tmp_path/'outputs/pallet_dataset_formal_v1/dataset'; formal.mkdir(parents=True)
    (formal/'manifest.json').write_text('{"formal":"protected"}')
    for name in cleanup.STORES:
        path = tmp_path/name; path.parent.mkdir(parents=True, exist_ok=True)
        with sqlite3.connect(path) as db:
            db.execute('CREATE TABLE reviews(id INTEGER PRIMARY KEY,payload TEXT)')
            db.execute('INSERT INTO reviews VALUES(1,?)', ('真实人工历史',))
    root = tmp_path/'outputs/review_round_001'
    (root/'cache').mkdir(parents=True); (root/'labels').mkdir(); (root/'reviews').mkdir()
    (root/'labels/human.jsonl').write_text('{"human":"保存原文"}\n')
    (root/'reviews/human.json').write_text('{"history":"不得删除"}')
    frame = np.zeros((12, 16, 4), np.float32)
    frame[..., :2] = np.arange(12*16*2).reshape(12, 16, 2); frame[..., 2:] = 1
    local = root/'cache/a.npz'
    np.savez(local, frame=frame)
    master = tmp_path/'outputs/cache_v5/frames/a.npz'; master.parent.mkdir(parents=True)
    master.write_bytes(local.read_bytes())
    frame_id = 'frame-1'
    (root/'cache_index.json').write_text(json.dumps({frame_id: str(local)}))
    views = root/'views'/hashlib.sha256(frame_id.encode()).hexdigest()[:20]; views.mkdir(parents=True)
    for name in cleanup.VIEW_NAMES:
        (views/name).write_bytes(cleanup.render_preview(frame, name))
    return tmp_path, root, local, master, views


def test_plan_does_not_delete_apply_removes_only_derived_and_restore_is_byte_exact(environment):
    project, root, local, master, views = environment
    original = {str(p): p.read_bytes() for p in (local, *views.iterdir())}
    human = {str(p): p.read_bytes() for p in (root/'labels/human.jsonl', root/'reviews/human.json')}
    out = project/'outputs/cleanup_test'
    plan = cleanup.plan(out)
    assert plan['deletion_counts'] == {'exact_master_cache_copy': 1, 'verified_native_preview_regeneration': 3}
    assert all(Path(p).read_bytes() == raw for p, raw in original.items())
    result = cleanup.apply(out, cleanup.digest(out/'plan.json'))
    assert result['deleted_files'] == 4 and all(not Path(p).exists() for p in original)
    assert all(Path(p).read_bytes() == raw for p, raw in human.items())
    assert master.exists() and result['all_human_stores_logically_unchanged']
    cleanup.restore(out)
    assert all(Path(p).read_bytes() == raw for p, raw in original.items())
    with pytest.raises(ValueError, match='already started'):
        cleanup.apply(out, cleanup.digest(out/'plan.json'))


def test_nonidentical_cache_and_nonregenerable_view_are_preserved(environment):
    project, root, local, master, views = environment
    # Different exact NPZ bytes do not qualify as duplicate deletion.
    master.write_bytes(master.read_bytes()+b'not-the-original')
    (views/'depth.png').write_bytes(b'possibly-user-modified')
    out = project/'outputs/cleanup_test'
    plan = cleanup.plan(out)
    assert 'exact_master_cache_copy' not in plan['deletion_counts']
    assert plan['deletion_counts']['verified_native_preview_regeneration'] == 2
    assert all(c['source'] == 'outputs/review_round_001/cache/a.npz' for c in plan['candidates'])
    cleanup.apply(out, cleanup.digest(out/'plan.json'))
    assert local.exists() and (views/'depth.png').read_bytes() == b'possibly-user-modified'


def test_external_document_reference_preserves_its_preview(environment):
    project, root, _, _, views = environment
    docs = project/'docs'; docs.mkdir()
    (docs/'example.md').write_text(str((views/'intensity.png').relative_to(project)))
    plan = cleanup.plan(project/'outputs/cleanup_test')
    assert all(c['path'] != str((views/'intensity.png').relative_to(project)) for c in plan['candidates'])


def test_changed_human_record_blocks_all_deletion(environment):
    project, root, local, _, _ = environment
    out = project/'outputs/cleanup_test'; cleanup.plan(out)
    (root/'labels/human.jsonl').write_text('new manual save')
    with pytest.raises(ValueError, match='Retained sources changed'):
        cleanup.apply(out, cleanup.digest(out/'plan.json'))
    assert local.exists() and not (out/'deletion_journal.jsonl').exists()


def test_changed_candidate_blocks_all_deletion(environment):
    project, _, local, _, _ = environment
    out = project/'outputs/cleanup_test'; cleanup.plan(out)
    local.write_bytes(b'changed')
    with pytest.raises(ValueError, match='Target changed'):
        cleanup.apply(out, cleanup.digest(out/'plan.json'))
    assert local.exists() and not (out/'deletion_journal.jsonl').exists()


def test_wrong_hash_blocks_all_deletion(environment):
    project, _, local, _, _ = environment
    out = project/'outputs/cleanup_test'; cleanup.plan(out)
    with pytest.raises(ValueError, match='Plan hash'):
        cleanup.apply(out, '0'*64)
    assert local.exists()


def test_open_files_are_not_cleanup_targets(environment, monkeypatch):
    project, _, local, _, _ = environment
    monkeypatch.setattr(cleanup, 'open_paths', lambda: {str(local)})
    plan = cleanup.plan(project/'outputs/cleanup_test')
    assert all(c['path'] != str(local.relative_to(project)) for c in plan['candidates'])


def test_path_escape_and_symlink_parents_are_rejected(tmp_path, monkeypatch):
    monkeypatch.setattr(cleanup, 'PROJECT', tmp_path)
    with pytest.raises(ValueError):
        cleanup.safe_path('../escape')
    with pytest.raises(ValueError):
        cleanup.safe_path('/absolute')
    (tmp_path/'outputs').symlink_to(tmp_path/'outside')
    with pytest.raises(ValueError, match='Symlinks'):
        cleanup.safe_path('outputs/review_round_001/cache/a.npz')
