"""Configuration for social-value wallet."""

from __future__ import annotations

import os
from dataclasses import dataclass

from .types import VALID_NETWORKS, SecretStr


VALID_BACKENDS = ("liquid", "spark")


@dataclass(frozen=True)
class SocialValueConfig:
    """Configuration for the social-value wallet.

    Values can be set directly or loaded from environment variables.
    Sensitive values are wrapped in SecretStr to prevent accidental logging.
    """

    breez_api_key: SecretStr
    backend: str = "liquid"  # "liquid" or "spark"
    network: str = "mainnet"  # "mainnet" or "testnet"
    working_dir: str = ".breez_data"
    max_balance_sat: int = 0  # 0 = no limit

    def __post_init__(self) -> None:
        if self.backend not in VALID_BACKENDS:
            raise ValueError(
                f"backend must be one of {VALID_BACKENDS}, got '{self.backend}'"
            )
        if self.network not in VALID_NETWORKS:
            raise ValueError(
                f"network must be one of {VALID_NETWORKS}, got '{self.network}'"
            )
        if self.max_balance_sat < 0:
            raise ValueError(
                f"max_balance_sat must be non-negative, got {self.max_balance_sat}"
            )
        if not self.breez_api_key:
            raise ValueError("breez_api_key is required")
        # Prevent path traversal in working_dir
        if ".." in self.working_dir or self.working_dir.startswith("/"):
            raise ValueError(
                f"working_dir must be a relative path without '..', got '{self.working_dir}'"
            )

    def __repr__(self) -> str:
        return (
            f"SocialValueConfig(breez_api_key=SecretStr('***'), "
            f"backend='{self.backend}', network='{self.network}', "
            f"working_dir='{self.working_dir}', max_balance_sat={self.max_balance_sat})"
        )

    @classmethod
    def from_env(cls) -> SocialValueConfig:
        """Load configuration from environment variables.

        Environment variables:
            BREEZ_API_KEY: Required. Breez SDK API key (free at breez.technology).
            SOCIAL_VALUE_BACKEND: Optional. 'liquid' or 'spark'. Default: liquid.
            SOCIAL_VALUE_NETWORK: Optional. 'mainnet' or 'testnet'. Default: mainnet.
            SOCIAL_VALUE_WORKING_DIR: Optional. Relative path for SDK data. Default: .breez_data.
            SOCIAL_VALUE_MAX_BALANCE: Optional. Max sats to hold. Default: 0 (no limit).
        """
        api_key = os.environ.get("BREEZ_API_KEY", "")
        if not api_key:
            raise ValueError(
                "BREEZ_API_KEY environment variable is required. "
                "Get a free key at https://breez.technology/sdk/"
            )

        max_balance_raw = os.environ.get("SOCIAL_VALUE_MAX_BALANCE", "0")
        try:
            max_balance = int(max_balance_raw)
        except ValueError:
            raise ValueError(
                f"SOCIAL_VALUE_MAX_BALANCE must be a number, got '{max_balance_raw}'"
            )

        return cls(
            breez_api_key=SecretStr(api_key),
            backend=os.environ.get("SOCIAL_VALUE_BACKEND", "liquid"),
            network=os.environ.get("SOCIAL_VALUE_NETWORK", "mainnet"),
            working_dir=os.environ.get("SOCIAL_VALUE_WORKING_DIR", ".breez_data"),
            max_balance_sat=max_balance,
        )
