"""
Hardware Anomaly Traps: Mathematical Verification of Gaussian Clicks
Instagram can detect standard `uniform` distributed clicks as bot-like.
This test ensures our click distributions follow a proper biological Gaussian curve.
"""

import os
import sys

# Ensure the GramAddict module is reachable
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))

import numpy as np

from GramAddict.core.device_facade import DeviceFacade


class MockDeviceFacade(DeviceFacade):
    def __init__(self):
        self.clicks = []

    def human_click(self, x, y):
        self.clicks.append((x, y))


class MockNode:
    def bounds(self):
        # returns left, top, right, bottom
        return (100, 500, 300, 600)  # Width = 200, Height = 100


def test_gaussian_distribution():
    device = MockDeviceFacade()
    node = MockNode()

    # Simulate 10,000 clicks
    for _ in range(10000):
        device.click(obj=node)

    xs = [c[0] for c in device.clicks]
    ys = [c[1] for c in device.clicks]

    mean_x = np.mean(xs)
    std_x = np.std(xs)

    mean_y = np.mean(ys)
    std_y = np.std(ys)

    print(f"Total Clicks: {len(device.clicks)}")
    print(f"X -> Mean: {mean_x:.2f} (Expected ~190 based on thumb bias), StdDev: {std_x:.2f} (Expected ~30)")
    print(f"Y -> Mean: {mean_y:.2f} (Expected ~555 based on thumb bias), StdDev: {std_y:.2f} (Expected ~15)")

    # Assertions
    assert 185 <= mean_x <= 195, "X Mean does not reflect the 45% thumb bias."
    assert 550 <= mean_y <= 560, "Y Mean does not reflect the 55% thumb bias."

    # Check for Normal Distribution using a simple heuristic (68-95-99.7 rule)
    within_1_std = sum(1 for x in xs if mean_x - std_x <= x <= mean_x + std_x) / len(xs)
    print(f"{within_1_std*100:.2f}% of X clicks within 1 standard deviation (should be ~68%)")
    assert 0.65 <= within_1_std <= 0.72, "Distribution is not Gaussian!"

    print("SUCCESS: Clicks pass the hardware anti-bot anomaly check!")


if __name__ == "__main__":
    test_gaussian_distribution()
