"""
Configuration management for the dxlabs CLI.
Handles loading and saving of the .dxlabs.json configuration file.
"""

import json
from pathlib import Path
from typing import Optional

from pydantic import BaseModel

CONFIG_FILE = ".dxlabs.json"


class Config(BaseModel):
    """
    Configuration model for dxlabs project settings.

    Attributes:
        bucket (str): The AWS S3 bucket name.
        project (str): The unique project identifier used as a prefix in S3.
        region (str): The AWS region for S3 operations.
        profile (Optional[str]): The AWS profile name to use for credentials.
    """

    bucket: str
    project: str
    region: Optional[str] = "ap-northeast-1"
    profile: Optional[str] = None


def load_config() -> Optional[Config]:
    """
    Loads the project configuration from the local .dxlabs.json file.

    Returns:
        Optional[Config]: The configuration object if found and valid, else None.
    """
    config_path = Path(CONFIG_FILE)
    if not config_path.exists():
        return None
    try:
        with open(config_path, "r") as f:
            data = json.load(f)
            return Config(**data)
    except Exception:
        return None


def save_config(
    bucket: str,
    project: str,
    region: str = "ap-northeast-1",
    profile: Optional[str] = None,
):
    """
    Saves the project configuration to a local .dxlabs.json file.

    Args:
        bucket (str): The S3 bucket name to use.
        project (str): The project name/prefix for storage.
        region (str): The AWS region (defaults to ap-northeast-1).
        profile (Optional[str]): The AWS profile name to use.
    """
    config = Config(bucket=bucket, project=project, region=region, profile=profile)
    with open(CONFIG_FILE, "w") as f:
        json.dump(config.model_dump(), f, indent=4)
