"""
Forensic Visual Artifact Audit Script.
Analyzes screenshots captured during browser tests to verify:
1. Valid PNG binary format and non-empty size.
2. Dimensions match canvas/viewport (e.g. 874x414 or similar).
3. Image is not blank, monochrome, or corrupted (checks color std dev, unique colors, channel variance).
4. Textures and elevation gradients are demonstrably present.
"""

import os
import sys
from PIL import Image
import numpy as np

SCREENSHOTS = [
    r"c:\Projects\FreeExile\.agents\teamwork\challenger_m4_1\biome_1_unobstructed.png",
    r"c:\Projects\FreeExile\.agents\teamwork\challenger_m4_1\biome_2_unobstructed.png",
    r"c:\Projects\FreeExile\.agents\teamwork\challenger_m4_1\biome_30_unobstructed.png",
    r"c:\Projects\FreeExile\.agents\teamwork\reviewer_m4_2\biome_3_independent_render.png",
    r"c:\Projects\FreeExile\.agents\teamwork\reviewer_m4_2\biome_10_independent_render.png",
]

def audit_visuals():
    print("--- FORENSIC VISUAL ARTIFACT AUDIT ---")
    all_clean = True

    for spath in SCREENSHOTS:
        if not os.path.exists(spath):
            print(f"FAIL: Screenshot not found: {spath}")
            all_clean = False
            continue

        size = os.path.getsize(spath)
        try:
            with Image.open(spath) as img:
                w, h = img.size
                mode = img.mode
                arr = np.array(img.convert("RGB"))
        except Exception as e:
            print(f"FAIL: Unable to open {spath}: {e}")
            all_clean = False
            continue

        # Color metrics
        std_per_channel = np.std(arr, axis=(0, 1))
        overall_std = float(np.mean(std_per_channel))

        # Center 100x100 patch unique colors
        cx, cy = w // 2, h // 2
        patch = arr[cy-50:cy+50, cx-50:cx+50]
        # Reshape to (10000, 3)
        flat_patch = patch.reshape(-1, 3)
        unique_colors_patch = len(np.unique(flat_patch, axis=0))

        # Full image unique colors
        flat_all = arr.reshape(-1, 3)
        unique_colors_total = len(np.unique(flat_all, axis=0))

        print(f"\nImage: {os.path.basename(spath)}")
        print(f"  Path: {spath}")
        print(f"  Size: {size:,} bytes | Dimensions: {w}x{h} | Mode: {mode}")
        print(f"  Channel StdDev (R,G,B): {std_per_channel[0]:.1f}, {std_per_channel[1]:.1f}, {std_per_channel[2]:.1f} | Overall: {overall_std:.1f}")
        print(f"  Center 100x100 Unique Colors: {unique_colors_patch:,} / 10,000")
        print(f"  Full Image Unique Colors: {unique_colors_total:,}")

        # Check heuristics:
        # A blank/monochrome canvas has std < 5 or unique_colors < 100
        if overall_std < 5.0 or unique_colors_patch < 200:
            print("  VIOLATION: Canvas appears blank, flat monochrome, or lacks texture detail!")
            all_clean = False
        else:
            print("  Status: AUTHENTIC RENDERED CANVAS DETECTED")

    if all_clean:
        print("\nOVERALL VISUAL ARTIFACT VERDICT: CLEAN")
    else:
        print("\nOVERALL VISUAL ARTIFACT VERDICT: INTEGRITY VIOLATION DETECTED")
        sys.exit(1)

if __name__ == "__main__":
    audit_visuals()
