import os
import pathlib
import random
import string

import pytest
from loguru import logger

from app import create_app
from helpers.time_helper import current_timestamp
import config

TMP_PATH = './tests/tmp/'
PWNDOC_DANGER_OVERRIDE = os.getenv("PWNDOC_DANGER_OVERRIDE", False) == 'True'

logger.log(
    'WARNING' if PWNDOC_DANGER_OVERRIDE else 'INFO',
    f"Tests can be destructive to PwnDoc. Those function are currently {'ENABLED' if PWNDOC_DANGER_OVERRIDE else 'DISABLED'}."
)


# This would be good to test endpoints, but currently requires active connection to PwnDoc.
@pytest.fixture()
def app():
    pathlib.Path(TMP_PATH).mkdir(parents=True, exist_ok=True)
    db_path = f'{TMP_PATH}/test_{current_timestamp()}_{"".join(random.choice(string.ascii_lowercase) for _ in range(6))}.db'
    config.DB_URI = f'sqlite:///{db_path}'
    config.RQ_DISABLED = True
    config.APP_INIT_PWNDOC_DISALLOW_WAITING = True

    config.PWNDOC_URL = 'https://localhost:8442' if PWNDOC_DANGER_OVERRIDE else config.PWNDOC_NO_CONNECTION_PLACEHOLDER

    app = create_app(skip_pwndoc=not PWNDOC_DANGER_OVERRIDE)
    app.config.update({
        "TESTING": True,
    })

    # other setup can go here

    yield app

    # clean up / reset resources here


@pytest.fixture()
def client(app):
    return app.test_client()


@pytest.fixture()
def runner(app):
    return app.test_cli_runner()
