from locust import HttpUser, task, between
import os
import re

LOGIN_PATH  = os.environ.get("LOGIN_PATH",  "")
LOGIN_EMAIL = os.environ.get("LOGIN_EMAIL", "")
LOGIN_PASS  = os.environ.get("LOGIN_PASS",  "")
TARGET_PATH = os.environ.get("TARGET_PATH", "/")


class WebUser(HttpUser):
    wait_time = between(1, 2)

    def on_start(self):
        if LOGIN_PATH and LOGIN_EMAIL:
            try:
                res = self.client.get(LOGIN_PATH, catch_response=True)
                match = re.search(r'name="_token"\s+value="([^"]+)"', res.text)
                csrf = match.group(1) if match else ""
                self.client.post(LOGIN_PATH, data={
                    "_token":   csrf,
                    "email":    LOGIN_EMAIL,
                    "password": LOGIN_PASS,
                }, allow_redirects=True)
            except Exception:
                pass

    @task
    def test_target(self):
        self.client.get(TARGET_PATH)
