"""Tests run the real HTTP server with the model call replaced by a stub: no API key, no cost."""

import json
import os
import threading
import unittest
import urllib.error
import urllib.request
from http.server import ThreadingHTTPServer
from unittest import mock

import meeting_actions as app

RESULT = app.ActionItems(summary="Agreed on the launch plan.",
                         items=[app.Item(task="Send the pricing draft", owner="Dana", due="Friday")])


class WebhookTest(unittest.TestCase):
    def setUp(self):
        self.calls, self.forwarded = [], []

        def fake_extract(transcript, meeting):
            self.calls.append((transcript, meeting))
            return RESULT

        class Handler(app.Handler):
            extract = staticmethod(fake_extract)
            forward = staticmethod(lambda url, text: self.forwarded.append((url, text)))

        self.handler = Handler
        self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
        threading.Thread(target=self.server.serve_forever, daemon=True).start()
        self.addCleanup(self.server.server_close)
        self.addCleanup(self.server.shutdown)
        env = mock.patch.dict(os.environ, {"WEBHOOK_SECRET": "s3cret"})
        env.start()
        self.addCleanup(env.stop)
        os.environ.pop("FORWARD_URL", None)

    def post(self, body, secret="s3cret", path="/webhook"):
        data = body if isinstance(body, bytes) else json.dumps(body).encode()
        headers = {"Content-Type": "application/json"}
        if secret is not None:
            headers["X-Webhook-Secret"] = secret
        request = urllib.request.Request(f"http://127.0.0.1:{self.server.server_port}{path}", data=data,
                                         headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=10) as response:
                return response.status, json.loads(response.read())
        except urllib.error.HTTPError as error:
            return error.code, json.loads(error.read())

    def test_returns_action_items(self):
        status, body = self.post({"transcript": "Dana will send the pricing draft by Friday.", "meeting": "Launch"})
        self.assertEqual(status, 200)
        self.assertEqual(body["items"], [{"task": "Send the pricing draft", "owner": "Dana", "due": "Friday"}])
        self.assertEqual(self.calls, [("Dana will send the pricing draft by Friday.", "Launch")])
        self.assertNotIn("forwarded", body)

    def test_wrong_or_missing_secret_is_rejected_before_the_model_is_called(self):
        self.assertEqual(self.post({"transcript": "x"}, secret="nope")[0], 401)
        self.assertEqual(self.post({"transcript": "x"}, secret=None)[0], 401)
        self.assertEqual(self.calls, [])

    def test_unset_server_secret_rejects_everything(self):
        with mock.patch.dict(os.environ, {"WEBHOOK_SECRET": ""}):
            self.assertEqual(self.post({"transcript": "x"}, secret="")[0], 401)
        self.assertEqual(self.calls, [])

    def test_bad_input_is_400_and_costs_nothing(self):
        for body in (b"not json", {"meeting": "no transcript"}, {"transcript": "   "}, {"transcript": 5}, [1, 2]):
            self.assertEqual(self.post(body)[0], 400, body)
        self.assertEqual(self.calls, [])

    def test_oversized_body_is_413(self):
        status, _ = self.post({"transcript": "a" * (app.MAX_BODY + 1)})
        self.assertEqual(status, 413)
        self.assertEqual(self.calls, [])

    def test_unknown_path_is_404(self):
        self.assertEqual(self.post({"transcript": "x"}, path="/other")[0], 404)

    def raw(self, request: bytes) -> bytes:
        import socket
        with socket.create_connection(("127.0.0.1", self.server.server_port), timeout=5) as sock:
            sock.sendall(request)
            sock.shutdown(socket.SHUT_WR)
            chunks = []
            while chunk := sock.recv(4096):
                chunks.append(chunk)
        return b"".join(chunks)

    def test_negative_content_length_is_400_not_an_unbounded_read(self):
        answer = self.raw(b"POST /webhook HTTP/1.1\r\nHost: x\r\nX-Webhook-Secret: s3cret\r\n"
                          b"Content-Length: -1\r\n\r\n" + b'{"transcript": "x"}')
        self.assertTrue(answer.startswith(b"HTTP/1.0 400"), answer[:60])
        self.assertEqual(self.calls, [])

    def test_non_ascii_secret_header_is_401_not_a_dropped_connection(self):
        answer = self.raw("POST /webhook HTTP/1.1\r\nHost: x\r\nX-Webhook-Secret: пароль\r\n"
                          "Content-Length: 2\r\n\r\n{}".encode("latin-1", "replace")
                          .replace(b"??????", "пароль".encode("utf-8")))
        self.assertTrue(answer.startswith(b"HTTP/1.0 401"), answer[:60])

    def test_malformed_request_line_gets_an_error_response(self):
        answer = self.raw(b"POST /webhook HTTP/9.9\r\n\r\n")
        self.assertIn(b"505", answer)  # the server answers instead of dropping the connection

    def test_deeply_nested_json_is_400(self):
        self.assertEqual(self.post(b"[" * 200_000)[0], 400)
        self.assertEqual(self.calls, [])

    def test_model_failure_is_502_without_leaking_details(self):
        def boom(transcript, meeting):
            raise RuntimeError("overloaded")

        self.handler.extract = staticmethod(boom)
        status, body = self.post({"transcript": "x"})
        self.assertEqual(status, 502)
        self.assertNotIn("overloaded", body["error"], "error details can quote the transcript")

    def test_digest_is_forwarded_when_configured(self):
        with mock.patch.dict(os.environ, {"FORWARD_URL": "https://hooks.example/abc"}):
            status, body = self.post({"transcript": "x", "meeting": "Launch"})
        self.assertEqual((status, body["forwarded"]), (200, True))
        self.assertEqual(self.forwarded, [("https://hooks.example/abc",
                                           "Launch: Agreed on the launch plan.\n"
                                           "- Send the pricing draft (Dana, Friday)")])

    def test_forward_failure_still_returns_items(self):
        def fail(url, text):
            raise OSError("connection refused")

        self.handler.forward = staticmethod(fail)
        with mock.patch.dict(os.environ, {"FORWARD_URL": "https://hooks.example/abc"}):
            status, body = self.post({"transcript": "x"})
        self.assertEqual((status, body["forwarded"]), (200, False))
        self.assertEqual(len(body["items"]), 1)
        self.assertNotIn("forward_error", body)


if __name__ == "__main__":
    unittest.main()
