from __future__ import annotations

import random
from dataclasses import dataclass
from datetime import datetime
import os


MANUAL_ORDER_RECEIVE_PRICE_MIN = 10
MANUAL_ORDER_RECEIVE_PRICE_MAX = 30
DISPATCH_PRICE_PERCENT_MIN = 60
DISPATCH_PRICE_PERCENT_MAX = 90


@dataclass(frozen=True)
class EnterpriseRegistrationData:
    phone: str
    password: str
    enterprise_name: str
    contact_name: str


def random_mainland_phone(prefix: str = "19") -> str:
    clean_prefix = "".join(ch for ch in prefix if ch.isdigit()) or "19"
    clean_prefix = clean_prefix[:3]
    remaining = 11 - len(clean_prefix)
    return clean_prefix + "".join(str(random.randint(0, 9)) for _ in range(remaining))


def manual_order_receive_price() -> str:
    explicit = os.getenv("E2E_MANUAL_ORDER_RECEIVE_PRICE", "").strip()
    if explicit:
        value = int(explicit)
        assert MANUAL_ORDER_RECEIVE_PRICE_MIN <= value <= MANUAL_ORDER_RECEIVE_PRICE_MAX, (
            "E2E_MANUAL_ORDER_RECEIVE_PRICE must be between "
            f"{MANUAL_ORDER_RECEIVE_PRICE_MIN} and {MANUAL_ORDER_RECEIVE_PRICE_MAX}, got {value}"
        )
        return str(value)
    return str(random.randint(MANUAL_ORDER_RECEIVE_PRICE_MIN, MANUAL_ORDER_RECEIVE_PRICE_MAX))


def random_dispatch_price_percent() -> str:
    explicit = os.getenv("E2E_DISPATCH_PRICE_PERCENT", "").strip()
    if explicit:
        value = int(explicit)
        assert DISPATCH_PRICE_PERCENT_MIN <= value <= DISPATCH_PRICE_PERCENT_MAX, (
            "E2E_DISPATCH_PRICE_PERCENT must be between "
            f"{DISPATCH_PRICE_PERCENT_MIN} and {DISPATCH_PRICE_PERCENT_MAX}, got {value}"
        )
        return str(value)
    return str(random.randint(DISPATCH_PRICE_PERCENT_MIN, DISPATCH_PRICE_PERCENT_MAX))


def default_dispatch_price_percent() -> str:
    existing = os.getenv("E2E_GENERATED_DISPATCH_PRICE_PERCENT", "").strip()
    if existing:
        return existing
    percent = random_dispatch_price_percent()
    os.environ["E2E_GENERATED_DISPATCH_PRICE_PERCENT"] = percent
    return percent


def configure_random_percent_dispatch(monkeypatch) -> str:
    percent = random_dispatch_price_percent()
    monkeypatch.setenv("E2E_S_FLOW_DISPATCH_PRICE_MODE", "percent")
    monkeypatch.setenv("E2E_S_FLOW_DISPATCH_PRICE_PERCENT", percent)
    monkeypatch.setenv("E2E_TASK_DISPATCH_PRICE_MODE", "percent")
    monkeypatch.setenv("E2E_TASK_DISPATCH_PRICE_PERCENT", percent)
    return percent


def enterprise_data(password: str, prefix: str, enterprise_prefix: str) -> EnterpriseRegistrationData:
    suffix = datetime.now().strftime("%m%d%H%M%S") + str(random.randint(100, 999))
    return EnterpriseRegistrationData(
        phone=random_mainland_phone(prefix),
        password=password,
        enterprise_name=f"{enterprise_prefix}{suffix}",
        contact_name=f"E2E联系人{suffix[-4:]}",
    )
