#!/usr/bin/env python3
"""Run repeatable black-box probes against the supplied benign target."""
import hashlib
import json
import subprocess
import sys
import tempfile
from pathlib import Path

HERE = Path(__file__).resolve().parent
TARGET = HERE / "mystery_manifest.py"

def run(args):
    return subprocess.run(
        [sys.executable, str(TARGET), *map(str, args)],
        text=True, capture_output=True, check=False
    )

def main():
    results = []

    # Probe 1: normal directory, nested file, hidden file and temporary suffix.
    sample = HERE / "sample_data"
    normal = run([sample])
    results.append({
        "probe": "normal_directory",
        "return_code": normal.returncode,
        "stdout_parses_as_json": _is_json(normal.stdout),
        "stderr": normal.stderr.strip(),
        "observed_file_paths": _paths(normal.stdout),
        "interpretation": "Observe inclusion/exclusion, nested traversal, and JSON shape."
    })

    # Probe 2: missing argument.
    missing = run([])
    results.append({
        "probe": "missing_argument",
        "return_code": missing.returncode,
        "stdout": missing.stdout.strip(),
        "stderr": missing.stderr.strip(),
        "interpretation": "Establish CLI usage behavior."
    })

    # Probe 3: nonexistent path.
    absent = run([HERE / "path_that_does_not_exist"])
    results.append({
        "probe": "nonexistent_path",
        "return_code": absent.returncode,
        "stdout": absent.stdout.strip(),
        "stderr": absent.stderr.strip(),
        "interpretation": "Establish failure behavior for an invalid input path."
    })

    # Probe 4: content sensitivity. Same path, altered bytes, compare hashes.
    with tempfile.TemporaryDirectory() as temp:
        item = Path(temp) / "sample.bin"
        item.write_bytes(b"alpha")
        first = run([temp])
        item.write_bytes(b"bravo")
        second = run([temp])
        first_hash = _hash_for(first.stdout, "sample.bin")
        second_hash = _hash_for(second.stdout, "sample.bin")
        results.append({
            "probe": "content_sensitivity",
            "return_code_first": first.returncode,
            "return_code_second": second.returncode,
            "hash_changed_after_content_change": first_hash != second_hash,
            "first_sha256": first_hash,
            "second_sha256": second_hash,
            "interpretation": "Test whether file content affects the reported digest."
        })

    output = {
        "lab": "AI-Assisted Software Reverse Engineering",
        "target": "mystery_manifest.py",
        "probe_count": len(results),
        "probes": results,
        "limitations": [
            "The target is a benign educational utility, not a commercial binary.",
            "Behavior is observed only for the listed test cases.",
            "No claim is made about untested operating systems or permission edge cases."
        ]
    }
    print(json.dumps(output, indent=2))
    return 0

def _is_json(text):
    try:
        json.loads(text)
        return True
    except (ValueError, TypeError):
        return False

def _paths(text):
    try:
        return [item["path"] for item in json.loads(text).get("files", [])]
    except (ValueError, TypeError, KeyError):
        return []

def _hash_for(text, path):
    try:
        return next(item["sha256"] for item in json.loads(text)["files"] if item["path"] == path)
    except (ValueError, TypeError, KeyError, StopIteration):
        return None

if __name__ == "__main__":
    raise SystemExit(main())
