import os

import boto3
import jsonlines
import pytest

PYTEST_TABLE_NAME = 'pytest'
DYNAMODB_ENDPOINT_URL = 'http://localhost:8000'
PK = 'id'
SK = 'sk'


# https://docs.pytest.org/en/7.1.x/reference/reference.html#pytest.hookspec.pytest_configure
def pytest_configure():
    os.environ['TZ'] = 'America/Sao_Paulo'
    os.environ['DYNAMODB_PARTITION_KEY'] = PK
    os.environ['DYNAMODB_SORT_KEY'] = SK
    os.environ['PYTEST_TABLE_NAME'] = PYTEST_TABLE_NAME


@pytest.fixture
def dynamodb_client():
    client = boto3.client('dynamodb', endpoint_url=DYNAMODB_ENDPOINT_URL)
    client.create_table(
        AttributeDefinitions=[
            {'AttributeName': PK, 'AttributeType': 'S'},
            {'AttributeName': SK, 'AttributeType': 'S'},
        ],
        TableName=PYTEST_TABLE_NAME,
        KeySchema=[
            {'AttributeName': PK, 'KeyType': 'HASH'},
            {'AttributeName': SK, 'KeyType': 'RANGE'},
        ],
        ProvisionedThroughput={
            'ReadCapacityUnits': 123,
            'WriteCapacityUnits': 123,
        },
    )

    yield client

    client.delete_table(TableName=PYTEST_TABLE_NAME)


@pytest.fixture()
def dynamodb_persistence_layer(dynamodb_client):
    from layercake.dynamodb import DynamoDBPersistenceLayer

    return DynamoDBPersistenceLayer(PYTEST_TABLE_NAME, dynamodb_client)


@pytest.fixture()
def dynamodb_seeds(dynamodb_client):
    with jsonlines.open('tests/seeds.jsonl') as lines:
        for line in lines:
            dynamodb_client.put_item(TableName=PYTEST_TABLE_NAME, Item=line)
