import random
import time
from typing import Dict, List, Any, Optional
from locust import HttpUser, task, between, SequentialTaskSet
import logging

from test_data import TestDataGenerator
from utils import ResponseValidator, data_manager

logger = logging.getLogger(__name__)


class APIWorkflowUser(HttpUser):
    """User that executes complex workflows"""

    wait_time = between(2, 8)
    weight = 2

    tasks = []

    def on_start(self):
        self.workflow_data = {}
        logger.info("Workflow user started")

    def on_stop(self):
        logger.info("Workflow user stopped")


class DataDependentFlow(SequentialTaskSet):
    """Flow that demonstrates data dependencies between requests"""

    @task
    def create_resource(self):
        resource_data = {
            'name': f"resource_{random.randint(1000, 9999)}",
            'type': random.choice(['document', 'image', 'video']),
            'metadata': {
                'created_by': 'load_test',
                'test_run': True
            }
        }

        response_data = self.user.make_request(
            method="post",
            url="/resources",
            json=resource_data
        )

        if response_data and 'id' in response_data:
            data_manager.store_shared_data('last_resource_id', response_data['id'])
            self.user.user_data['resource_id'] = response_data['id']

    @task
    def update_resource(self):
        resource_id = self.user.user_data.get('resource_id') or data_manager.get_shared_data('last_resource_id')
        if resource_id:
            update_data = {
                'name': f"updated_resource_{random.randint(1000, 9999)}",
                'status': 'active'
            }
            self.user.make_request(
                method="put",
                url=f"/resources/{resource_id}",
                json=update_data
            )

    @task
    def get_resource(self):
        resource_id = self.user.user_data.get('resource_id')
        if resource_id:
            self.user.make_request(
                method="get",
                url=f"/resources/{resource_id}"
            )

    @task
    def delete_resource(self):
        resource_id = self.user.user_data.get('resource_id')
        if resource_id:
            self.user.make_request(
                method="delete",
                url=f"/resources/{resource_id}"
            )
            self.user.user_data.pop('resource_id', None)


class ComplexFlowUser(HttpUser):
    """User that executes complex, realistic flows"""

    wait_time = between(3, 10)
    weight = 1

    tasks = [
        DataDependentFlow
    ]
