"""Storage survey stays read-only and reports physical allocation honestly."""
import ast
import importlib.util
import os
from pathlib import Path

import pytest

PATH = Path(__file__).resolve().parents[1]/'scripts/analyze_remaining_output_storage.py'
SPEC = importlib.util.spec_from_file_location('remaining_storage', PATH)
survey = importlib.util.module_from_spec(SPEC); SPEC.loader.exec_module(survey)


def test_capacity_does_not_double_count_hardlinked_extents(tmp_path):
    path = tmp_path/'original'; path.write_bytes(b'a'*8192)
    link = tmp_path/'second_name'; os.link(path, link)
    before = path.read_bytes(); result = survey.capacity([path, link])
    assert result['files'] == 2
    assert result['allocated_bytes'] == path.stat().st_blocks*512
    assert result['hardlinked_files_needing_separate_review'] == 2
    assert result['allocation_not_a_verified_net_reclaim_guarantee']
    assert path.read_bytes() == before


def test_symlink_entries_are_excluded_from_inventory(tmp_path):
    root = tmp_path/'root'; root.mkdir()
    actual = root/'actual'; actual.write_text('keep')
    (root/'symlink').symlink_to(actual)
    assert survey.files(root) == [actual]


def test_existing_output_is_rejected_before_any_source_reads(tmp_path, monkeypatch):
    monkeypatch.setattr(survey, 'PROJECT', tmp_path)
    out = tmp_path/'outputs/audit'; out.mkdir(parents=True)
    (out/'notes.md').write_text('user notes')
    with pytest.raises(ValueError, match='fresh'):
        survey.analyze(out)
    assert (out/'notes.md').read_text() == 'user notes'


def test_empty_capacity_does_not_invent_space():
    result = survey.capacity([])
    assert result['allocated_bytes'] == result['gib'] == result['files'] == 0


def test_analysis_has_no_deletion_relink_or_model_initialization_calls():
    tree = ast.parse(PATH.read_text()); imports = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            imports.update(alias.name for alias in node.names)
        if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
            assert node.func.attr not in ('unlink', 'rmtree', 'rmdir', 'rename', 'replace', 'link', 'symlink_to', 'chmod')
    assert not imports.intersection({'torch', 'ultralytics', 'rfdetr'})
