"""Reproduce the two no-proxy wreq inventory requests."""
import asyncio
import json
from importlib.metadata import version
import platform
import sys
import time
from datetime import datetime, timedelta, timezone
from pathlib import Path

import wreq

HERE = Path(__file__).resolve().parent
TARGETS = {
    "wikipedia_web_scraping": "https://en.wikipedia.org/wiki/Web_scraping",
    "amazon_search_laptop": "https://www.amazon.com/s?k=laptop",
}
BLOCK_MARKERS = ("robot check", "enter the characters", "please complete the captcha", "access denied", "verify you are human")


async def main(target_id: str) -> None:
    url = TARGETS[target_id]
    started = datetime.now(timezone.utc).isoformat()
    begin = time.perf_counter()
    row = {
        "target_id": target_id, "url": url, "started_at": started,
        "tool": "wreq", "tool_version": version("wreq"),
        "python_version": platform.python_version(), "platform": platform.platform(),
        "command": f"{sys.executable} {' '.join(sys.argv)}",
        "config": {"client": "wreq.Client", "emulation": "Chrome134", "timeout_seconds": 15, "no_proxy": True},
        "network": "local host direct outbound", "proxy_mode": "none",
        "resource_use_file": "wikipedia-resource.txt" if target_id.startswith("wikipedia") else "amazon-resource.txt",
    }
    try:
        client = wreq.Client(emulation=wreq.Emulation.Chrome134, timeout=timedelta(seconds=15))
        response = await client.get(url, no_proxy=True)
        body = await response.text()
        artifact = f"{target_id}.txt"
        (HERE / artifact).write_text(body, encoding="utf-8")
        lowered = body.lower()
        status = response.status.as_int()
        row.update(status=status, response_chars=len(body), response_bytes=len(body.encode("utf-8")), raw_response=artifact,
                   has_expected_content=("web scraping" in lowered if target_id.startswith("wikipedia") else "laptop" in lowered),
                   block_markers=[m for m in BLOCK_MARKERS if m in lowered],
                   usable_content=(status == 200 and ("web scraping" in lowered if target_id.startswith("wikipedia") else "laptop" in lowered)
                                   and not any(m in lowered for m in BLOCK_MARKERS)))
    except Exception as exc:
        row.update(error=f"{type(exc).__name__}: {exc}", usable_content=False)
    row["elapsed_seconds"] = round(time.perf_counter() - begin, 3)
    (HERE / f"{target_id}.json").write_text(json.dumps(row, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(row, indent=2))


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))
