import os
from dataclasses import dataclass


DEFAULT_CORS_ALLOW_ORIGIN_REGEX = (
    r"^https?://("
    r"localhost|127\.0\.0\.1|"
    r"10\.\d{1,3}\.\d{1,3}\.\d{1,3}|"
    r"192\.168\.\d{1,3}\.\d{1,3}|"
    r"172\.(1[6-9]|2\d|3[0-1])\.\d{1,3}\.\d{1,3}"
    r")(:\d+)?$"
)


def _parse_csv_env(value: str) -> tuple[str, ...]:
    return tuple(part.strip() for part in value.split(",") if part.strip())


@dataclass(frozen=True)
class Settings:
    app_name: str
    database_url: str
    client_name: str
    client_email: str
    client_password: str
    client_tenant_id: str
    admin_name: str
    admin_email: str
    admin_password: str
    auth_secret: str
    cors_allow_origins: tuple[str, ...]
    cors_allow_origin_regex: str

    @classmethod
    def from_env(cls) -> "Settings":
        return cls(
            app_name=os.getenv("APP_NAME", "Data Entry App API"),
            database_url=os.getenv("DATABASE_URL", "sqlite:///./data_entry_app.db"),
            client_name=os.getenv("CLIENT_NAME", "Hunter Premium Produce"),
            client_email=os.getenv("CLIENT_EMAIL", "operator@example.com"),
            client_password=os.getenv("CLIENT_PASSWORD", "changeme"),
            client_tenant_id=os.getenv("CLIENT_TENANT_ID", "hunter-premium-produce"),
            admin_name=os.getenv("ADMIN_NAME", "Lean 101"),
            admin_email=os.getenv("ADMIN_EMAIL", "admin@lean101.local"),
            admin_password=os.getenv("ADMIN_PASSWORD", "lean101-admin"),
            auth_secret=os.getenv("AUTH_SECRET", "lean-101-local-dev-secret"),
            cors_allow_origins=_parse_csv_env(
                os.getenv(
                    "CORS_ALLOW_ORIGINS",
                    "http://localhost:5173,http://localhost:5174,http://127.0.0.1:5173,http://127.0.0.1:5174",
                )
            ),
            cors_allow_origin_regex=os.getenv("CORS_ALLOW_ORIGIN_REGEX", DEFAULT_CORS_ALLOW_ORIGIN_REGEX),
        )


settings = Settings.from_env()
