import uuid

from pydantic import Field, field_validator

from data_exchange_agent.config.sections.base_section_config import BaseSectionConfig


class ApplicationConfig(BaseSectionConfig):
    """Configuration class for application settings."""

    max_parallel_tasks: int | None = Field(
        default=None, ge=1, le=100, description="Maximum number of parallel tasks"
    )
    task_fetch_interval: int | None = Field(
        default=None, ge=1, description="Interval in seconds to fetch tasks when idle"
    )
    lease_refresh_interval: int | None = Field(
        default=None, ge=1, description="Interval in seconds to refresh task leases"
    )
    debug_mode: bool | None = Field(default=None, description="Enable debug mode")
    affinity: str | None = Field(
        default=None, description="Agent affinity for task assignment"
    )
    agent_id: str = Field(
        default_factory=lambda: str(uuid.uuid4()), description="Unique agent identifier"
    )
    snowflake_database_for_metadata: str | None = Field(
        default=None,
        description="Snowflake database holding orchestrator task-queue objects (must match orchestrator)",
    )
    snowflake_schema_for_data_migration_metadata: str | None = Field(
        default=None,
        description="Schema for PULL_TASKS / COMPLETE_TASK / FAIL_TASK (must match orchestrator)",
    )

    @field_validator("affinity")
    @classmethod
    def validate_affinity(cls, v: str | None) -> str | None:
        """Validate that affinity is not empty or whitespace-only."""
        if v is not None and not v.strip():
            raise ValueError("Affinity cannot be an empty string.")
        return v

    @field_validator(
        "snowflake_database_for_metadata",
        "snowflake_schema_for_data_migration_metadata",
        mode="before",
    )
    @classmethod
    def normalize_optional_metadata_identifier(cls, v: str | None) -> str | None:
        """Strip Snowflake identifier fields; treat blank strings as unset."""
        if v is None:
            return None
        if not isinstance(v, str):
            return v
        s = v.strip()
        return s if s else None

    def __repr__(self) -> str:
        """Return string representation of application configuration."""
        return (
            f"ApplicationConfig(agent_id={self.agent_id}, "
            f"max_parallel_tasks={self.max_parallel_tasks}, "
            f"task_fetch_interval={self.task_fetch_interval}, "
            f"lease_refresh_interval={self.lease_refresh_interval}, "
            f"debug_mode={self.debug_mode}, "
            f"affinity={self.affinity}, "
            f"snowflake_database_for_metadata={self.snowflake_database_for_metadata}, "
            f"snowflake_schema_for_data_migration_metadata="
            f"{self.snowflake_schema_for_data_migration_metadata})"
        )
