"""Colony config loading and defaults."""

from __future__ import annotations

import os
from pathlib import Path

import yaml

from fliiq.runtime.colony.models import ColonyConfig


def load_colony_config(colony_dir: Path) -> ColonyConfig:
    """Load config.yaml from .colony/ or return defaults."""
    config_path = colony_dir / "config.yaml"
    if config_path.is_file():
        data = yaml.safe_load(config_path.read_text()) or {}
        config = ColonyConfig(**data)
    else:
        config = ColonyConfig()

    # Fall back to existing Telegram env var if colony-specific chat_id not set
    if not config.telegram_chat_id:
        allowed = os.environ.get("TELEGRAM_ALLOWED_CHAT_IDS", "").strip()
        if allowed:
            config.telegram_chat_id = allowed.split(",")[0].strip()

    return config


def save_colony_config(colony_dir: Path, config: ColonyConfig) -> None:
    """Save config to .colony/config.yaml."""
    config_path = colony_dir / "config.yaml"
    config_path.parent.mkdir(parents=True, exist_ok=True)
    config_path.write_text(yaml.dump(config.model_dump(), default_flow_style=False, sort_keys=False))


def next_experiment_id(colony_dir: Path) -> int:
    """Determine next experiment ID from existing state."""
    state_file = colony_dir / "state" / "colony_state.yaml"
    if state_file.is_file():
        data = yaml.safe_load(state_file.read_text()) or {}
        return data.get("experiment_id", 0) + 1
    return 1
