"""Network-free helper regressions. Pass --scale 10000 for the synthetic scale exercise."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from hashlib import sha256
import io
import json
import os
import statistics
import sys
import tempfile
import time
import unittest
from unittest.mock import patch

import site_index as helper


def encode(value):
    return json.dumps(value, separators=(",", ":")).encode("utf-8")


def make_plan(domain, path):
    return {
        "domain": domain, "routes": [{"routeId": "docs-home", "pathTemplate": "/docs",
            "tags": ["docs"], "outlinks": [path]}], "actions": [], "workflowStates": [],
    }


class Edition:
    def __init__(self, records):
        self.requests = []
        self.read_sizes = []
        self.files = {}
        plans, rows = [], []
        for plan in records:
            row = encode(plan)
            domain = plan["domain"]
            path = f"plans/{domain}.json"
            self.files[path] = row
            rows.append(row + b"\n")
            plans.append({"domain": domain, "path": path, "fileSha256": "sha256:" + sha256(row).hexdigest()})
        bundle = self.files["plans.jsonl"] = b"".join(rows)
        manifest = self.files["manifest.json"] = encode({
            "schemaVersion": "hopper.site-index.edition-manifest.v1", "editionVersion": helper.EDITION,
            "plans": plans, "files": [{"path": "plans.jsonl", "byteLength": len(bundle),
                                      "sha256": "sha256:" + sha256(bundle).hexdigest()}],
        })
        self.digest = sha256(manifest).hexdigest()

    def open(self, url, timeout):
        if not url.startswith(helper.SOURCE + "/"):
            raise AssertionError("unexpected origin")
        name = url.removeprefix(helper.SOURCE + "/")
        self.requests.append(name)
        if name == "plans.jsonl":
            sizes = self.read_sizes

            class Stream(io.BytesIO):
                def read(self, n=-1):
                    sizes.append(n)
                    return super().read(n)

            return Stream(self.files[name])
        return io.BytesIO(self.files[name])


def restart():
    helper.catalog.cache_clear()
    helper.read_plan.cache_clear()


@contextmanager
def install(edition):
    restart()
    with tempfile.TemporaryDirectory() as cache, patch.dict(os.environ, {"XDG_CACHE_HOME": cache}), \
            patch.object(helper, "MANIFEST_DIGEST", edition.digest), patch.object(helper, "urlopen", edition.open):
        try:
            yield
        finally:
            restart()


class HelperTests(unittest.TestCase):
    def setUp(self):
        self.edition = Edition([make_plan("docs.github.com", "/en/rest"), make_plan("github.com", "/issues"),
                                make_plan("other.example", "/api-reference")])
        self.enterContext(install(self.edition))

    def test_scoped_question_and_local_private_miss(self):
        result = [{"kind": "linkedPath", "domain": "docs.github.com", "path": "/en/rest"}]
        self.assertEqual(helper.find_routes("Where is GitHub’s REST API reference?"), result)
        self.assertEqual(helper.find_routes("GitHub REST API"), result)
        self.assertEqual(helper.find_routes("GitHub quantum archaeology"), [])
        self.assertEqual(helper.site_map(" HTTPS://intranet.local/path?token=fictional "), {"status": "unindexed"})
        self.assertEqual(helper.site_map("127.0.0.1"), {"status": "unindexed"})
        self.assertEqual(helper.site_map(" DOCS.GITHUB.COM ")["routes"][0]["links"], ["/en/rest"])
        self.assertEqual(self.edition.requests, ["manifest.json", "plans/docs.github.com.json", "plans/github.com.json"])
        restart()
        self.assertEqual(helper.find_routes("GitHub REST API"), result)
        self.assertEqual(len(self.edition.requests), 3)

    def test_exact_search_and_disk_index_reuse(self):
        self.assertEqual(helper.find_routes("api-reference"), [{"kind": "linkedPath", "domain": "other.example",
                                                                "path": "/api-reference"}])
        self.assertEqual(helper.find_routes("en/res")[0]["path"], "/en/rest")
        self.assertEqual(helper.find_routes("ts"), [])
        self.assertEqual(helper.find_routes('x" OR docs'), [])
        self.assertEqual(helper.find_routes("missing"), [])
        self.assertEqual(len(helper.find_routes("api reference")), 2)
        self.assertEqual(self.edition.requests, ["manifest.json", "plans.jsonl"])
        restart()
        with patch.object(helper, "urlopen", side_effect=AssertionError("Unexpected network read")):
            self.assertEqual(helper.find_routes("/en/rest")[0]["path"], "/en/rest")
            self.assertEqual(helper.list_sites(1, 1)["domains"], ["github.com"])
        self.assertEqual(set(self.edition.read_sizes), {65536})

    def test_invalid_inputs(self):
        for term in ("", "a" * 101, "with\x00nul"):
            with self.assertRaises(ValueError):
                helper.find_routes(term)
        for page in ((-1, 1), (0, 0), (0, 1001)):
            with self.assertRaises(ValueError):
                helper.list_sites(*page)

    def test_untrusted_manifest_plan_and_partial_index(self):
        with patch.dict(self.edition.files, {"manifest.json": b"{}"}), self.assertRaises(ValueError):
            helper.list_sites()
        with patch.dict(self.edition.files, {"plans/github.com.json": b"{}"}), self.assertRaises(ValueError):
            helper.site_map("github.com")
        bundle = self.edition.files["plans.jsonl"]
        for bad in (bundle[:-1], b"!" + bundle[1:], bundle + b"extra"):
            with patch.dict(self.edition.files, {"plans.jsonl": bad}), self.assertRaises(ValueError):
                helper.find_routes("issues")
        self.assertEqual(helper.find_routes("issues")[0]["path"], "/issues")

    def test_two_cold_clients_share_one_search_index(self):
        with ThreadPoolExecutor(max_workers=2) as pool:
            one, two = list(pool.map(helper.find_routes, ["api-reference", "/en/rest"]))
        self.assertEqual(one[0]["domain"], "other.example")
        self.assertEqual(two[0]["domain"], "docs.github.com")
        self.assertEqual(self.edition.requests.count("plans.jsonl"), 1)


def scale(domains):
    """Synthetic .example records exercise the supported paths, storage and network bounds."""
    edition = Edition(make_plan(f"project{i:05}.example", f"/api/reference/task-{i:05}") for i in range(domains))
    last = domains - 1
    domain = f"project{last:05}.example"
    path = f"/api/reference/task-{last:05}"
    with install(edition):
        started = time.perf_counter()
        assert helper.site_map(domain)["domain"] == domain
        lookup_ms = (time.perf_counter() - started) * 1000
        assert edition.requests == ["manifest.json", f"plans/{domain}.json"]
        assert helper.list_sites(last, 1)["domains"] == [domain]
        started = time.perf_counter()
        expected = [{"kind": "linkedPath", "domain": domain, "path": path}]
        assert helper.find_routes(path) == expected
        build_ms = (time.perf_counter() - started) * 1000
        restart()
        warm = []
        for _ in range(25):
            started = time.perf_counter()
            assert helper.find_routes(path) == expected
            warm.append((time.perf_counter() - started) * 1000)
        assert len(helper.find_routes("api")) == helper.RESULT_LIMIT
        assert edition.requests == ["manifest.json", f"plans/{domain}.json", "plans.jsonl"]
        assert set(edition.read_sizes) == {65536}
        print(json.dumps({"kind": "offline synthetic fixture", "domains": domains, "routesAndLinkedPaths": 2 * domains,
                          "manifestBytes": len(edition.files["manifest.json"]), "jsonlBytes": len(edition.files["plans.jsonl"]),
                          "coldMapFiles": 2, "additionalSearchBootstrapFiles": 1, "warmNetworkReads": 0,
                          "streamReadBytes": max(edition.read_sizes), "coldMapMs": round(lookup_ms, 2),
                          "firstCrossSiteSearchMs": round(build_ms, 2), "warmLookupMedianMs": round(statistics.median(warm), 2),
                          "warmSamples": len(warm), "sqliteBytes": (helper.cache_dir() / "routes-v1.sqlite3").stat().st_size}))


if __name__ == "__main__":
    if len(sys.argv) == 3 and sys.argv[1] == "--scale":
        scale(int(sys.argv[2]))
    else:
        unittest.main()
