"""Verify the Plant Finder HTTP contract against fresh local fixture instances."""

import concurrent.futures
import hashlib
import http.client
import json
import os
from pathlib import Path
import queue
import re
import secrets
import subprocess
import tempfile
import threading
import time
import unittest
import uuid


PACK = Path(__file__).resolve().parents[1]
PROJECT = PACK / "PlantFinder.Api"
DLL = PROJECT / "bin" / "Debug" / "net10.0" / "PlantFinder.Api.dll"
CONNECTOR = PACK / "connector" / "plant-finder.swagger.json"
FIND = "/v1/plants/find"
MATCH_REQUEST = {"zone": 7, "light": "shade", "soil": "wet", "size": 5, "native": True, "fall": True}
MISSING = object()
CATALOG_LOOKUP = "Catalog lookup started"


class LabProcess:
    def __init__(self, *, content_root=PROJECT, credentials=None, **settings):
        self.content_root = content_root
        self.credentials = credentials if credentials is not None else {
            caller: (f"test-subject-{caller}", secrets.token_hex(32)) for caller in ("a", "b")
        }
        self.keys = {alias: key for alias, (_, key) in self.credentials.items()}
        self.process = None
        self.reader = None
        self.logs = []
        self.port = None
        self.settings = {
            "Enabled": "true",
            "PerUserDailyQuota": "100",
            "GlobalDailyQuota": "100",
            "PerUserRequestsPerMinute": "120",
            "SimulateCatalogUnavailable": "false",
            "AllowRemoteHttp": "false",
            **settings,
        }

    def __enter__(self):
        # Clear inherited app settings so the suite always runs in fixture mode.
        env = {
            key: value for key, value in os.environ.items()
            if not key.lower().startswith((
                "plantfinder__", "aspnetcore_", "dotnet_environment", "kestrel__", "logging__"
            ))
        }
        env.update({
            "ASPNETCORE_ENVIRONMENT": "Development",
            "Logging__LogLevel__Default": "Information",
            "Logging__LogLevel__Microsoft.Hosting.Lifetime": "Information",
            "NO_COLOR": "1",
        })
        for name, value in self.settings.items():
            if value is not None:
                env[f"PlantFinder__{name}"] = str(value)
        for index, (subject, key) in enumerate(self.credentials.values()):
            env[f"PlantFinder__Callers__{index}__Subject"] = subject
            env[f"PlantFinder__Callers__{index}__KeySha256"] = hashlib.sha256(key.encode("ascii")).hexdigest()

        lines = queue.Queue()
        self.process = subprocess.Popen(
            ["dotnet", str(DLL), "--urls=http://127.0.0.1:0"],
            cwd=self.content_root,
            env=env,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            encoding="utf-8",
            errors="replace",
        )

        def collect_output():
            for line in self.process.stdout:
                self.logs.append(line)
                lines.put(line)
            lines.put(None)

        self.reader = threading.Thread(target=collect_output, daemon=True)
        self.reader.start()
        try:
            deadline = time.monotonic() + 15
            while time.monotonic() < deadline:
                line = lines.get(timeout=max(0.01, deadline - time.monotonic()))
                if line is None:
                    break
                address = re.search(r"Now listening on: http://127\.0\.0\.1:(\d+)", line)
                if address:
                    self.port = int(address[1])
                    if self.request("GET", "/healthz")[0] == 200:
                        return self
                    break
        except (queue.Empty, OSError, http.client.HTTPException):
            pass
        self.__exit__(None, None, None)
        raise RuntimeError(f"Loopback API did not start.\n{self.safe_log()}")

    def __exit__(self, *_):
        if self.process.poll() is None:
            self.process.terminate()
            try:
                self.process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                self.process.kill()
                self.process.wait(timeout=5)
        self.reader.join(timeout=5)
        self.process.stdout.close()

    def safe_log(self):
        output = "".join(self.logs)
        for key in self.keys.values():
            output = output.replace(key, "[redacted test key]")
        return output

    def request(self, method, path, payload=MISSING, headers=None):
        headers = dict(headers or {})
        body = None
        if payload is not MISSING:
            headers.setdefault("Content-Type", "application/json")
            body = payload if isinstance(payload, bytes) else json.dumps(payload).encode("utf-8")
        connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=8)
        try:
            connection.request(method, path, body=body, headers=headers)
            response = connection.getresponse()
            content = response.read()
            response_headers = {key.lower(): value for key, value in response.getheaders()}
            if content and "json" in response_headers.get("content-type", ""):
                content = json.loads(content)
            return response.status, response_headers, content
        finally:
            connection.close()

    def find(self, caller="a", payload=MATCH_REQUEST, idem=MISSING, *, content_type="application/json"):
        headers = {"Content-Type": content_type}
        if caller is not None:
            headers["X-Plant-Finder-Key"] = self.keys.get(caller, caller)
        if idem is MISSING:
            idem = str(uuid.uuid4())
        if idem is not None:
            headers["Idempotency-Key"] = idem
        return self.request("POST", FIND, payload, headers)


def fire_concurrently(send, inputs):
    start = threading.Barrier(len(inputs), timeout=8)

    def send_after_signal(value):
        start.wait()
        return send(value)

    with concurrent.futures.ThreadPoolExecutor(max_workers=len(inputs)) as pool:
        return list(pool.map(send_after_signal, inputs))


class PlantFinderHttpTests(unittest.TestCase):
    def assert_problem(self, response, status, code=None):
        actual_status, headers, body = response
        self.assertEqual(actual_status, status, body)
        self.assertIn("application/problem+json", headers.get("content-type", ""))
        self.assertEqual(body["status"], status)
        self.assertTrue(headers.get("x-request-id"))
        self.assertEqual(body["traceId"], headers["x-request-id"])
        if code is not None:
            self.assertEqual(body["code"], code)
        if code in {"per_user_quota", "global_quota"}:
            self.assertGreater(int(headers["retry-after"]), 0)
            self.assertLessEqual(int(headers["retry-after"]), 86400)
        return headers

    def assert_lookups(self, app, count):
        entries = [json.loads(line) for line in app.safe_log().splitlines()]
        self.assertEqual(sum(entry["Message"] == CATALOG_LOOKUP for entry in entries), count)

    def test_contract_projects_only_public_fields_and_excludes_incomplete_rows(self):
        with LabProcess() as app:
            status, headers, response = app.find()
            self.assertEqual(status, 200, response)
            self.assertIn("application/json", headers["content-type"])
            self.assertEqual(set(response), {"kind", "message", "matches"})
            self.assertEqual(response["kind"], "match")
            self.assertEqual([item["id"] for item in response["matches"]], ["G-103", "G-104"])
            for item in response["matches"]:
                self.assertEqual(set(item), {"id", "name", "source", "reason"})
                self.assertTrue(all(isinstance(value, str) and value for value in item.values()))
                self.assertEqual(item["source"], "#" + item["id"])
            self.assertIn("exceeds the preferred 5 ft.", response["matches"][0]["reason"])

            status, _, response = app.find(payload={"zone": 7, "light": "shade", "soil": "dry"})
            self.assertEqual(status, 200, response)
            self.assertEqual(response["kind"], "no-match")
            self.assertEqual(response["matches"], [])
        self.assert_lookups(app, 2)

    def test_connector_operation_and_response_schema_match_runtime(self):
        connector = json.loads(CONNECTOR.read_text(encoding="utf-8"))
        self.assertEqual(connector["swagger"], "2.0")
        self.assertEqual(connector["schemes"], ["https"])
        self.assertTrue(connector["host"].endswith(".invalid"))
        operation = connector["paths"][FIND.removeprefix(connector["basePath"])]["post"]
        self.assertEqual(operation["operationId"], "FindPlants")
        self.assertEqual(connector["security"], [{"plantFinderKey": []}])
        security = connector["securityDefinitions"]["plantFinderKey"]
        self.assertEqual((security["type"], security["in"], security["name"]),
                         ("apiKey", "header", "X-Plant-Finder-Key"))
        parameters = {(entry["in"], entry["name"]): entry for entry in operation["parameters"]}
        request_key = parameters["header", "Idempotency-Key"]
        self.assertTrue(request_key["required"])
        self.assertTrue(parameters["body", "criteria"]["required"])
        criteria_schema = connector["definitions"]["PlantCriteria"]
        self.assertEqual(set(criteria_schema["required"]), {"zone", "light", "soil"})
        size_schema = criteria_schema["properties"]["size"]
        self.assertEqual(size_schema["type"], "number")
        self.assertEqual((size_schema["minimum"], size_schema["maximum"]), (1, 200))
        self.assertTrue({"200", "400", "401", "403", "409", "413", "415", "429", "503"}
                        <= set(operation["responses"]))

        result_schema = connector["definitions"]["PlantResult"]
        match_schema = connector["definitions"]["PlantMatch"]
        with LabProcess() as app:
            idempotency_key = "pilot:call_1.2-review"
            self.assertIsNotNone(re.fullmatch(request_key["pattern"], idempotency_key))
            status, _, response = app.find(payload={**MATCH_REQUEST, "size": 5.5}, idem=idempotency_key)
            self.assert_problem(app.find(idem="X" * (request_key["minLength"] - 1)),
                                400, "invalid_idempotency_key")
            self.assert_problem(app.find(idem="X" * (request_key["maxLength"] + 1)),
                                400, "invalid_idempotency_key")
            for allowed in (size_schema["minimum"], size_schema["maximum"]):
                self.assertEqual(app.find(payload={**MATCH_REQUEST, "size": allowed})[0], 200)
            for excluded in (size_schema["minimum"] - 0.1, size_schema["maximum"] + 0.1):
                self.assert_problem(app.find(payload={**MATCH_REQUEST, "size": excluded}), 400, "invalid_request")
        self.assertEqual(status, 200, response)
        self.assertEqual(set(response), set(result_schema["required"]))
        self.assertLessEqual(len(response["matches"]), result_schema["properties"]["matches"]["maxItems"])
        for item in response["matches"]:
            self.assertEqual(set(item), set(match_schema["required"]))

    def test_unauthorized_and_invalid_input_do_not_consume_quota(self):
        with LabProcess(PerUserDailyQuota=1, GlobalDailyQuota=1) as app:
            self.assert_problem(app.find(caller=None), 401)
            self.assert_problem(app.find(caller="0" * 64), 401)
            self.assert_problem(app.find(idem=None), 400)
            self.assert_problem(app.find(payload=b'{"zone":'), 400)
            self.assert_problem(app.find(payload=b'{"zone":7,"zone":8,"light":"shade","soil":"wet"}'),
                                400, "invalid_request")
            self.assert_problem(app.find(payload={**MATCH_REQUEST, "extra": "synthetic"}), 400, "invalid_request")
            self.assert_problem(app.find(payload={"light": "shade", "soil": "wet"}), 400)
            self.assert_problem(app.find(payload={**MATCH_REQUEST, "zone": 20}), 400)
            self.assert_problem(app.find(payload={**MATCH_REQUEST, "light": "moonlight"}), 400)
            self.assert_problem(app.find(content_type="text/plain"), 415, "unsupported_media_type")
            self.assert_problem(app.find(content_type="application/json; charset=latin1"), 415, "unsupported_media_type")
            self.assert_problem(app.find(payload=json.dumps(MATCH_REQUEST).encode() + b" " * 4096),
                                413, "payload_too_large")
            self.assertEqual(app.find(content_type="application/json; charset=utf-8")[0], 200)
        self.assert_lookups(app, 1)

    def test_idempotency_replays_responses_and_rejects_a_payload_change(self):
        with LabProcess(PerUserDailyQuota=1) as app:
            idem = str(uuid.uuid4())
            first = app.find(idem=idem)
            replay = app.find(payload=dict(reversed(list(MATCH_REQUEST.items()))), idem=idem)
            conflict = app.find(payload={**MATCH_REQUEST, "soil": "dry"}, idem=idem)
            self.assertEqual(first[0], 200, first[2])
            self.assertEqual(replay[0], 200, replay[2])
            self.assertEqual(replay[1].get("idempotency-replayed"), "true")
            self.assertEqual(first[2], replay[2])
            self.assert_problem(conflict, 409)
            self.assert_problem(app.find(), 429, "per_user_quota")
            self.assertEqual(app.find(caller="b", idem=idem)[0], 200)
        self.assert_lookups(app, 2)

    def test_concurrent_replays_reserve_once(self):
        with LabProcess(PerUserDailyQuota=1, GlobalDailyQuota=1) as app:
            idem = str(uuid.uuid4())
            responses = fire_concurrently(lambda value: app.find(idem=value), [idem] * 24)
            self.assertTrue(all(response[0] == 200 for response in responses), responses)
            self.assertTrue(all(response[2] == responses[0][2] for response in responses))
            originals = [response for response in responses if "idempotency-replayed" not in response[1]]
            self.assertEqual(len(originals), 1)
        self.assert_lookups(app, 1)

    def test_concurrent_per_user_quota_does_not_limit_another_user(self):
        with LabProcess(PerUserDailyQuota=3, GlobalDailyQuota=40) as app:
            responses = fire_concurrently(app.find, ["a"] * 24)
            self.assertEqual(sum(response[0] == 200 for response in responses), 3)
            for response in responses:
                if response[0] != 200:
                    self.assert_problem(response, 429, "per_user_quota")
            self.assertEqual(app.find(caller="b")[0], 200)
        self.assert_lookups(app, 4)

    def test_concurrent_global_quota_is_shared_before_catalog_lookup(self):
        with LabProcess(PerUserDailyQuota=30, GlobalDailyQuota=5) as app:
            responses = fire_concurrently(app.find, ["a", "b"] * 12)
            self.assertEqual(sum(response[0] == 200 for response in responses), 5)
            for response in responses:
                if response[0] != 200:
                    self.assert_problem(response, 429, "global_quota")
        self.assert_lookups(app, 5)

    def test_per_user_rate_limit_returns_retry_after(self):
        with LabProcess(PerUserRequestsPerMinute=2) as app:
            idem = str(uuid.uuid4())
            self.assertEqual(app.find(idem=idem)[0], 200)
            replay = app.find(idem=idem)
            self.assertEqual(replay[0], 200)
            self.assertEqual(replay[1].get("idempotency-replayed"), "true")
            headers = self.assert_problem(app.find(), 429, "rate_limit")
            self.assertGreater(int(headers["retry-after"]), 0)
            self.assertLessEqual(int(headers["retry-after"]), 60)
            self.assertEqual(app.find(caller="b")[0], 200)
        self.assert_lookups(app, 2)

    def test_disabled_catalog_runs_zero_lookups(self):
        with LabProcess(Enabled="false", SimulateCatalogUnavailable="true") as app:
            for caller in ("a", "b"):
                self.assert_problem(app.find(caller=caller), 503, "disabled")
        self.assert_lookups(app, 0)

    def test_kill_switch_pauses_existing_keys_and_resumes_without_a_restart(self):
        config = json.loads((PROJECT / "appsettings.json").read_text(encoding="utf-8"))
        with tempfile.TemporaryDirectory() as temp:
            root = Path(temp)
            config_path = root / "appsettings.json"

            def publish_enabled(enabled):
                config["PlantFinder"]["Enabled"] = enabled
                new_config = root / "next-settings.json"
                new_config.write_text(json.dumps(config), encoding="utf-8")
                new_config.replace(config_path)

            def wait_for_status(app, expected):
                deadline = time.monotonic() + 5
                while True:
                    response = app.find(idem=idem)
                    if response[0] == expected:
                        return response
                    self.assertLess(time.monotonic(), deadline, response)
                    time.sleep(0.05)

            publish_enabled(True)
            idem = str(uuid.uuid4())
            with LabProcess(content_root=root, Enabled=None) as app:
                self.assertEqual(app.find(idem=idem)[0], 200)
                publish_enabled(False)
                self.assert_problem(wait_for_status(app, 503), 503, "disabled")
                self.assertEqual(app.request("GET", "/healthz")[0], 200)
                publish_enabled(True)
                replay = wait_for_status(app, 200)
                self.assertEqual(replay[1].get("idempotency-replayed"), "true")
                self.assertEqual(app.find()[0], 200)
            self.assert_lookups(app, 2)

    def test_overlapping_secrets_share_subject_quota_then_old_secret_is_rejected(self):
        old_key, new_key = secrets.token_hex(32), secrets.token_hex(32)
        new = {"new": ("rotation-subject", new_key)}
        overlap = {"old": ("rotation-subject", old_key), **new}
        with LabProcess(credentials=overlap, PerUserDailyQuota=1) as app:
            idem = str(uuid.uuid4())
            self.assertEqual(app.find(caller="old", idem=idem)[0], 200)
            replay = app.find(caller="new", idem=idem)
            self.assertEqual(replay[0], 200)
            self.assertEqual(replay[1].get("idempotency-replayed"), "true")
            self.assert_problem(app.find(caller="new"), 429, "per_user_quota")
        self.assert_lookups(app, 1)

        with LabProcess(credentials=new) as app:
            self.assert_problem(app.find(caller=old_key), 401, "unauthorized")
            self.assertEqual(app.find(caller="new")[0], 200)
        self.assert_lookups(app, 1)

    def test_failed_catalog_attempt_counts_and_replays_without_another_lookup(self):
        with LabProcess(PerUserDailyQuota=1, SimulateCatalogUnavailable="true") as app:
            idem = str(uuid.uuid4())
            first = app.find(idem=idem)
            self.assert_problem(first, 503, "catalog_unavailable")
            replay = app.find(idem=idem)
            headers = self.assert_problem(replay, 503, "catalog_unavailable")
            self.assertEqual(headers.get("idempotency-replayed"), "true")
            self.assertEqual(first[2]["detail"], replay[2]["detail"])
            self.assertNotEqual(first[2]["traceId"], replay[2]["traceId"])
            self.assert_problem(app.find(), 429, "per_user_quota")
        self.assert_lookups(app, 1)

    def test_diagnostics_include_lookup_without_key_subject_or_request_contents(self):
        marker = "private-marker-" + secrets.token_hex(12)
        idem = str(uuid.uuid4())
        with LabProcess() as app:
            status, headers, _ = app.find(idem=idem)
            self.assertEqual(status, 200)
            self.assert_problem(app.find(payload={**MATCH_REQUEST, "light": marker}), 400)
        self.assert_lookups(app, 1)
        logs = "".join(app.logs)
        self.assertIn(headers["x-request-id"], logs)
        for value in (*app.keys.values(), "test-subject-a", marker, idem):
            self.assertFalse(value in logs, "Safe diagnostic output includes a private test value")


if __name__ == "__main__":
    if not DLL.is_file():
        raise SystemExit("Build first with: dotnet build PlantFinder.Api/PlantFinder.Api.csproj")
    unittest.main(verbosity=2)
