# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.utils import clear_user_cache
from devplacepy import project_files
from devplacepy.project_files import ProjectFileError
from devplacepy.services.devii.actions.dispatcher import (
    confirmation_error,
    _is_confirmed,
)
_counter_project_visibility = [0]
def _signup_project_visibility():
    _counter_project_visibility[0] += 1
    name = f"pv{int(time.time() * 1000)}{_counter_project_visibility[0]}"
    session = requests.Session()
    session.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,
    )
    row = get_table("users").find_one(username=name)
    return name, row["uid"], row["api_key"]
def _make_admin_project_visibility():
    name, uid, key = _signup_project_visibility()
    get_table("users").update({"uid": uid, "role": "Admin"}, ["uid"])
    clear_user_cache(uid)
    return name, uid, key
def _h_project_visibility(key=None):
    headers = {"Accept": "application/json"}
    if key:
        headers["X-API-KEY"] = key
    return headers
def _create_project_project_visibility(key, title, is_private=False):
    data = {
        "title": title,
        "description": "visibility test",
        "project_type": "software",
        "status": "In Development",
    }
    if is_private:
        data["is_private"] = "on"
    r = requests.post(f"{BASE_URL}/projects/create", headers=_h_project_visibility(key), data=data)
    assert r.status_code == 200, r.text
    return r.json()["data"]
def _project_uid(slug):
    return get_table("projects").find_one(slug=slug)["uid"]
def _write_project_visibility(key, slug, path, content):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/files/write",
        headers=_h_project_visibility(key),
        data={"path": path, "content": content},
        allow_redirects=False,
    )
def _set_private(key, slug, value):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/private",
        headers=_h_project_visibility(key),
        data={"value": 1 if value else 0},
        allow_redirects=False,
    )
def _set_readonly(key, slug, value):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/readonly",
        headers=_h_project_visibility(key),
        data={"value": 1 if value else 0},
        allow_redirects=False,
    )
def _list_slugs(key=None, user_uid=None):
    params = {"user_uid": user_uid} if user_uid else None
    r = requests.get(f"{BASE_URL}/projects", headers=_h_project_visibility(key), params=params)
    return [p["slug"] for p in r.json()["projects"]]


def test_private_files_hidden_from_guest(app_server):
    _, _, key = _signup_project_visibility()
    slug = _create_project_project_visibility(key, "Private Files", is_private=True)["slug"]
    _write_project_visibility(key, slug, "secret.txt", "classified")
    assert (
        requests.get(f"{BASE_URL}/projects/{slug}/files", headers=_h_project_visibility()).status_code
        == 404
    )
    assert (
        requests.get(
            f"{BASE_URL}/projects/{slug}/files/raw",
            params={"path": "secret.txt"},
            headers=_h_project_visibility(),
        ).status_code
        == 404
    )
    assert (
        requests.get(f"{BASE_URL}/projects/{slug}/files", headers=_h_project_visibility(key)).status_code
        == 200
    )


def test_readonly_unchanged_content(app_server):
    _, _, key = _signup_project_visibility()
    slug = _create_project_project_visibility(key, "Readonly Content")["slug"]
    _write_project_visibility(key, slug, "a.txt", "original")
    _set_readonly(key, slug, True)
    _write_project_visibility(key, slug, "a.txt", "tampered")
    body = requests.get(
        f"{BASE_URL}/projects/{slug}/files/raw",
        params={"path": "a.txt"},
        headers=_h_project_visibility(key),
    ).json()
    assert body["content"] == "original"
