from __future__ import annotations

import os
from dataclasses import dataclass


@dataclass
class DobbyConfig:
    port: int = 8420
    host: str = "127.0.0.1"
    max_concurrent_agents: int = 5
    default_timeout: int = 1800  # 30 minutes
    gpu_poll_interval: int = 300  # 5 minutes
    results_dir: str = "results"
    db_path: str = "dobby.db"
    api_key: str | None = None  # Bearer token for API auth; None = no auth
    webhook_url: str | None = None  # POST here on task completion/failure
    stale_timeout: int = 1800  # seconds with no log update before task is stale
    hub_url: str = ""  # Public-facing URL (e.g. "https://dobby.example.com"); empty = local only
    github_url: str = ""  # GitHub repo URL (e.g. "https://github.com/org/dobby"); empty = hide link

    @classmethod
    def from_dict(cls, d: dict) -> DobbyConfig:
        """Create a DobbyConfig by merging the provided dict over defaults."""
        defaults = cls()
        valid_fields = {f.name for f in cls.__dataclass_fields__.values()}
        kwargs = {k: v for k, v in d.items() if k in valid_fields}
        for key, value in kwargs.items():
            setattr(defaults, key, value)
        return defaults

    @classmethod
    def load(cls, path: str) -> DobbyConfig:
        """Load config from a YAML file. Returns defaults if file doesn't exist."""
        if not os.path.exists(path):
            return cls()
        import yaml
        with open(path) as f:
            data = yaml.safe_load(f) or {}
        return cls.from_dict(data)
