"""Acceptance pooling cannot introduce annotation writes or cross-origin redirects."""
from concurrent.futures import ThreadPoolExecutor
from http.server import BaseHTTPRequestHandler,ThreadingHTTPServer
import threading

import pytest

from scripts.review_http_pool import ReadOnlyHTTP


@pytest.fixture
def server():
    connections=set();posts=[];attempts=[]
    class Handler(BaseHTTPRequestHandler):
        protocol_version='HTTP/1.1'
        def log_message(self,*_):pass
        def reply(self,status,raw=b'ok',headers=None):
            self.send_response(status);self.send_header('Content-Length',str(len(raw)))
            for key,value in (headers or {}).items():self.send_header(key,value)
            self.end_headers();self.wfile.write(raw)
        def do_GET(self):
            connections.add(self.client_address)
            if self.path=='/private':return self.reply(200 if 'fixture=saved' in self.headers.get('Cookie','') else 401)
            if self.path=='/retry':
                attempts.append(1)
                return self.reply(503 if len(attempts)<2 else 200)
            if self.path=='/redirect':return self.reply(302,headers={'Location':'https://unrelated.invalid/'})
            if self.path=='/wrong':return self.reply(400)
            self.reply(200)
        def do_POST(self):
            posts.append(self.path);self.rfile.read(int(self.headers.get('Content-Length','0')))
            self.reply(200,headers={'Set-Cookie':'fixture=saved; Path=/; HttpOnly'})
    http=ThreadingHTTPServer(('127.0.0.1',0),Handler);http.daemon_threads=True
    thread=threading.Thread(target=http.serve_forever,daemon=True);thread.start()
    try:yield f'http://127.0.0.1:{http.server_port}',connections,posts,attempts
    finally:http.shutdown();http.server_close();thread.join()


def test_reuses_connection_and_preserves_authenticated_pool_reads(server):
    base,connections,posts,_=server
    with ReadOnlyHTTP(base) as client:
        for _ in range(3):assert client.get('/').content==b'ok'
        assert len(connections)==1
        client.login('fixture-secret',gallery=True)
        with ThreadPoolExecutor(max_workers=3) as pool:assert all(pool.map(lambda _:client.get('/private').status_code==200,range(9)))
    assert posts==['/api/review/login']


@pytest.mark.parametrize('method,path,data',[
    ('POST','/api/annotations/a',{'key':'secret'}),('POST','/api/delete-object/a',{'key':'secret'}),
    ('DELETE','/api/review/annotations/a',None),('POST','/api/login?next=elsewhere',{'key':'secret'}),
    ('POST','/api/login',{'key':'secret','polygon':[]}),('GET','https://foreign.invalid/',None),
    ('GET','//foreign.invalid/',None),('GET','/private',{'key':'secret'}),('POST','/api/review/logout',{})])
def test_refuses_every_non_login_mutation_and_foreign_route(server,method,path,data):
    base,_,posts,_=server
    with ReadOnlyHTTP(base) as client:
        with pytest.raises(ValueError):client.request(path,method=method,data=data)
    assert not posts


def test_only_transient_failures_are_retried_and_redirects_never_followed(server,monkeypatch):
    base,_,_,attempts=server;monkeypatch.setattr('scripts.review_http_pool.time.sleep',lambda _:None)
    with ReadOnlyHTTP(base) as client:
        assert client.get('/retry').status_code==200 and len(attempts)==2 and len(client.retries)==1
        with pytest.raises(ValueError,match='302'):client.get('/redirect')
        with pytest.raises(ValueError,match='400'):client.get('/wrong')
        assert len(client.retries)==1


@pytest.mark.parametrize('base',['https://user:password@example.com','file:///tmp/fixture','https://example.com/path','https://example.com?key=secret'])
def test_no_credentials_or_paths_in_service_origin(base):
    with pytest.raises(ValueError):ReadOnlyHTTP(base)
