from copy import deepcopy

import pytest

from pallet import pallet_review_ptunnel as transport


def row():
    return dict(id='pallet-description-round5-new',type='http',host='127.0.0.1',port=3418,target='127.0.0.1:3418',status='connected',url='https://example123.tunnel.phineas.top')


def test_only_named_local_review_profile_is_accepted():
    value=row();before=deepcopy(value)
    assert transport.validate_route(value,mode='new',port=3418)==before and value==before


@pytest.mark.parametrize('change',[
    {'id':'unrelated'}, {'host':'0.0.0.0'}, {'port':3419}, {'target':'127.0.0.1:49374'}, {'type':'tcp'},
    {'url':'https://foo.trycloudflare.com'}, {'url':'https://x.tunnel.phineas.top.evil.test'},
    {'url':'http://x.tunnel.phineas.top'}, {'url':'https://user:pass@x.tunnel.phineas.top'},
    {'url':'https://x.tunnel.phineas.top?token=secret'}, {'url':'https://x.tunnel.phineas.top/path'},
])
def test_wrong_profile_upstream_or_origin_rejected(change):
    with pytest.raises(ValueError):transport.validate_route({**row(),**change},mode='new',port=3418)


def test_existing_profile_is_adopted_without_create_or_global_shutdown(monkeypatch):
    value=row();monkeypatch.setattr(transport,'profiles',lambda:{value['id']:value})
    monkeypatch.setattr(transport,'command',lambda *a,**k:(_ for _ in ()).throw(AssertionError('unexpected create/stop')))
    assert transport.ensure_route('new',3418)==value


def test_missing_profile_creates_exact_one_loopback_HTTP_route(monkeypatch):
    calls=[];monkeypatch.setattr(transport,'profiles',lambda:{'unrelated':{}})
    monkeypatch.setattr(transport,'command',lambda args,timeout=30:(calls.append((args,timeout)) or row()))
    transport.ensure_route('new',3418)
    assert calls==[(['http','3418','--host','127.0.0.1','--name','pallet-description-round5-new','--json'],260)]


def test_pending_profile_is_not_duplicated_or_deleted(monkeypatch):
    monkeypatch.setattr(transport,'profiles',lambda:{row()['id']:{**row(),'status':'reconnecting'}})
    monkeypatch.setattr(transport,'command',lambda *a,**k:(_ for _ in ()).throw(AssertionError('duplicated/deleted route')))
    with pytest.raises(ValueError,match='reconnecting'):transport.ensure_route('new',3418)


def test_unexpected_existing_upstream_is_not_rebound(monkeypatch):
    monkeypatch.setattr(transport,'profiles',lambda:{row()['id']:{**row(),'port':49374}})
    with pytest.raises(ValueError):transport.ensure_route('new',3418)


def test_listener_check_matches_HTTPServer_reuse_and_rejects_live_listener():
    import socket,sys
    from pathlib import Path
    sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
    from serve_pallet_description_ptunnel import port_available
    with socket.socket() as listener:
        listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);listener.bind(('127.0.0.1',0));listener.listen()
        port=listener.getsockname()[1]
        assert not port_available(port)
        with socket.create_connection(('127.0.0.1',port)) as client:
            connection,_=listener.accept();connection.close()
    assert port_available(port)


def test_missing_transport_config_fails_without_starting_Cloudflare(tmp_path,monkeypatch):
    import sys
    from pathlib import Path
    sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts'))
    import serve_pallet_description_ptunnel as service
    monkeypatch.setattr(service,'REVIEW_SETS',{'new':{'managed':tmp_path}})
    monkeypatch.setattr(service,'make_runtime',lambda mode:(_ for _ in ()).throw(AssertionError('must not construct/start a fallback runtime')))
    with pytest.raises(ValueError,match='Cloudflare fallback is disabled'):service.main('new')
