# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import init_db, get_table
from devplacepy import project_files as pf
from devplacepy.project_files import ProjectFileError
@pytest.fixture(autouse=True)
def _init_db_project_file_lines():
    init_db()
    yield
_pid = [0]
def _project():
    _pid[0] += 1
    pid = f"plines-{_pid[0]}"
    user = {"uid": f"plines-owner-{_pid[0]}"}
    return pid, user
_counter_project_file_lines = [0]
def _signup_project_file_lines():
    _counter_project_file_lines[0] += 1
    name = f"pl{int(time.time() * 1000)}{_counter_project_file_lines[0]}"
    requests.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    return name, get_table("users").find_one(username=name)["api_key"]
def _h_project_file_lines(key):
    return {"X-API-KEY": key, "Accept": "application/json"}
def _create_project_project_file_lines(key, title):
    r = requests.post(
        f"{BASE_URL}/projects/create",
        headers=_h_project_file_lines(key),
        data={
            "title": title,
            "description": "lines test",
            "project_type": "software",
            "status": "In Development",
        },
    )
    assert r.status_code == 200, r.text
    return r.json()["data"]
def _write_project_file_lines(key, slug, path, content):
    r = requests.post(
        f"{BASE_URL}/projects/{slug}/files/write",
        headers=_h_project_file_lines(key),
        data={"path": path, "content": content},
        allow_redirects=False,
    )
    assert r.status_code in (200, 302), r.text
def _raw_project_file_lines(key, slug, path):
    return requests.get(
        f"{BASE_URL}/projects/{slug}/files/raw", headers=_h_project_file_lines(key), params={"path": path}
    ).json()
class _FakeResponse:
    def __init__(self, status_code=200):
        self.status_code = status_code
class _FakeClient:
    authenticated = True
    username = "u"

    def __init__(self):
        self.calls = []

    async def call(
        self, method, path, params=None, data=None, file_field=None, headers=None
    ):
        self.calls.append((method, path))
        return _FakeResponse()
def _make_dispatcher():
    import devplacepy.services.devii.actions.dispatcher as disp
    from devplacepy.services.devii.actions.catalog import PLATFORM_CATALOG

    d = disp.Dispatcher.__new__(disp.Dispatcher)
    d._actions = PLATFORM_CATALOG.by_name()
    d._client = _FakeClient()
    d._read_files = set()
    return disp, d


def test_http_read_lines(app_server):
    _, key = _signup_project_file_lines()
    proj = _create_project_project_file_lines(key, "HTTP Read Lines")
    slug = proj["slug"] or proj["uid"]
    _write_project_file_lines(key, slug, "f.txt", "a\nb\nc\nd")
    r = requests.get(
        f"{BASE_URL}/projects/{slug}/files/lines",
        headers=_h_project_file_lines(key),
        params={"path": "f.txt", "start": 2, "end": 3},
    )
    assert r.status_code == 200
    body = r.json()
    assert body["lines"] == ["b", "c"]
    assert body["total_lines"] == 4


def test_http_lines_missing_file_404(app_server):
    _, key = _signup_project_file_lines()
    proj = _create_project_project_file_lines(key, "HTTP Lines 404")
    slug = proj["slug"] or proj["uid"]
    r = requests.get(
        f"{BASE_URL}/projects/{slug}/files/lines",
        headers=_h_project_file_lines(key),
        params={"path": "nope.txt"},
    )
    assert r.status_code == 404
