#!/usr/bin/env python3
"""
API ENGINE FOUNDRY v2.1 - TERMUX LOCAL TRI-STAR PROXY & TAR WELL ESCAPEMENT

- Non-rooted 3-Gate Traffic Sanitizer
- PE Variance: Sweet Spot [368-370], Randomized Bracket [342-396]
- Timed Escapement Release: 11,000ms

Install on the phone (Termux):
    curl -fsSL https://tinyradr.lovable.app/agent/tristar_proxy.py -o ~/tristar_proxy.py
    python ~/tristar_proxy.py
"""

import asyncio
import random
import re

LISTEN_HOST = "127.0.0.1"
LISTEN_PORT = 8888
PE_BASELINE = 369
ESCAPEMENT_INTERVAL = 11.0  # 11 seconds


def calculate_pe_variance(data: bytes) -> int:
    if not data:
        return PE_BASELINE
    words = [int.from_bytes(data[i : i + 2], byteorder="big") for i in range(0, len(data) - 1, 2)]
    return (sum(words) % 1000) if words else PE_BASELINE


def gate1_intake_scrape(data: bytes) -> tuple[bool, bytes, str]:
    variance = calculate_pe_variance(data)
    # 1. Sweet Spot (+/- 1)
    if 368 <= variance <= 370:
        return True, data, "SWEET_SPOT"
    # 2. Randomized Allowance Bracket (342 to 396) - Entropy to prevent clocking
    elif 342 <= variance <= 396:
        if random.choice([True, False]):
            return True, data, "RANDOM_ALLOWANCE"
        return False, data[: int(len(data) * 0.85)], "RANDOM_SCRAPE"
    # 3. Hard Boundary Scrape Zone
    return False, data[: int(len(data) * 0.85)], "HARD_SCRAPE"


def gate2_mezzanine_scrub(data: bytes) -> bytes:
    payload = data.decode("utf-8", errors="ignore")
    # PII Scrubbing
    payload = re.sub(
        r'(imei|imsi|mac_address|location_lat|location_lon)=["\'][^"\']+["\']',
        r'\1="[SCRUBBED]"',
        payload,
        flags=re.IGNORECASE,
    )
    return payload.encode("utf-8")


async def gate3_timed_release(writer: asyncio.StreamWriter, data: bytes):
    await asyncio.sleep(ESCAPEMENT_INTERVAL)  # 11,000ms clockwork release
    writer.write(data)
    await writer.drain()


async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
    try:
        while not reader.at_eof():
            data = await reader.read(4096)
            if not data:
                break
            _in_bounds, processed_data, _status = gate1_intake_scrape(data)
            clean_payload = gate2_mezzanine_scrub(processed_data)
            await gate3_timed_release(writer, clean_payload)
    except Exception:
        pass
    finally:
        writer.close()
        await writer.wait_closed()


async def main():
    server = await asyncio.start_server(handle_client, LISTEN_HOST, LISTEN_PORT)
    print(f"[+] Tri-Star Proxy Active on {LISTEN_HOST}:{LISTEN_PORT}")
    async with server:
        await server.serve_forever()


if __name__ == "__main__":
    asyncio.run(main())
