import os
from dataclasses import dataclass

import jsonlines
import pytest

PYTEST_TABLE_NAME = 'pytest'
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['USER_TABLE'] = PYTEST_TABLE_NAME


@dataclass
class LambdaContext:
    function_name: str = 'test'
    memory_limit_in_mb: int = 128
    invoked_function_arn: str = 'arn:aws:lambda:eu-west-1:809313241:function:test'
    aws_request_id: str = '52fdfc07-2182-154f-163f-5f0f9a621d72'


@pytest.fixture
def lambda_context() -> LambdaContext:
    return LambdaContext()


@pytest.fixture
def dynamodb_client():
    from boto3clients import dynamodb_client as client

    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)
