import time
from pathlib import Path

import aiohttp
import pytest
import requests

from clarabot_nano.utility.path.validate import normalize_absolute_path
from clarabot_nano_tests.indexer.extractor.utility import ExtractorTesterBase
from clarabot_nano_tests.testing.file import temp_path


# TODO: decide if this is useful at all or not
@pytest.mark.asyncio
async def Xtest_indexer_extractor_perf(tmpdir, indexer_extractor_tester: ExtractorTesterBase):
    p = Path(normalize_absolute_path(temp_path(tmpdir)))
    data = (
        "This small text will be perfect to test the communication overhead of the extractor client.\n"
        "Oh, indeed! It will be very nice!"
    ).encode("utf-8")
    p.write_bytes(data)
    extract_url = f"http://127.0.0.1:{indexer_extractor_tester.ec.tika_port}/tika"
    headers = {"Accept": "text/xml"}

    # Test the actual implementation.
    extractor = indexer_extractor_tester.create_extractor()
    t = -time.perf_counter()
    for _ in range(120):
        await extractor.extract(p)
    t += time.perf_counter()
    print("_ implementation ", t)

    # warmup tika
    for i in range(10):
        with requests.Session() as s:
            t = -time.perf_counter()
            for _ in range(120):
                r = s.put(url=extract_url, data=data, headers=headers)
                _ = r.content
            t += time.perf_counter()
            print("_ requests xx ", i, t)

    # Test with aiohttp.ClientSession stream
    async with aiohttp.ClientSession() as s:
        t = -time.perf_counter()
        for _ in range(120):
            with p.open("rb") as f:
                async with s.put(url=extract_url, data=f, headers=headers) as r:
                    async for _ in r.content.iter_any():
                        pass
        t += time.perf_counter()
        print("_ aiohttp stream ", t)

    # Test with aiohttp.ClientSession bulk
    async with aiohttp.ClientSession() as s:
        t = -time.perf_counter()
        for _ in range(120):
            async with s.put(url=extract_url, data=data, headers=headers) as r:
                _ = await r.read()
        t += time.perf_counter()
        print("_ aiohttp bulk   ", t)

    # Test with requests.Session bulk
    with requests.Session() as s:
        t = -time.perf_counter()
        for _ in range(120):
            r = s.put(url=extract_url, data=data, headers=headers)
            _ = r.content
        t += time.perf_counter()
        print("_ requests bulk  ", t)

    # Test the actual implementation.
    extractor = indexer_extractor_tester.create_extractor()
    t = -time.perf_counter()
    for _ in range(120):
        await extractor.extract(p)
    t += time.perf_counter()
    print("_ implementation ", t)

    assert False, "PASSED"
