"""
Path constants and utilities for the data exchange agent.

This module defines standard file and directory paths used throughout the
data exchange agent, including database paths, configuration paths, and
result storage locations.
"""

import os

from datetime import datetime


def _get_home_dir() -> str:
    """
    Get the user's home directory path.

    Returns:
        str: The absolute path to the user's home directory.

    """
    return os.path.expanduser("~")


APP_FOLDER_PATH = os.path.join(_get_home_dir(), ".data_exchange_agent")
ROOT_DBS_FOLDER_PATH = os.path.join(APP_FOLDER_PATH, "dbs")
ROOT_LOGS_FOLDER_PATH = os.path.join(APP_FOLDER_PATH, "logs")
ROOT_RESULTS_FOLDER_PATH = os.path.join(APP_FOLDER_PATH, "result_data")
DB_TASKS_FILE_PATH = os.path.join(ROOT_DBS_FOLDER_PATH, "data_exchange_tasks.db")

# Configuration file name
CONFIGURATION_FILE_NAME = "configuration.toml"

# Default configuration file path (in user's home .data_exchange_agent folder)
DEFAULT_CONFIGURATION_FILE_PATH = os.path.join(APP_FOLDER_PATH, CONFIGURATION_FILE_NAME)


def get_configuration_file_path() -> str:
    """
    Find the configuration file path by searching in multiple locations.

    Search order:
    1. Current working directory (./configuration.toml)
    2. User's app folder (~/.data_exchange_agent/configuration.toml)

    Returns:
        str: Path to the configuration file (first found, or default if none exist)

    """
    # Locations to search (in priority order)
    search_paths = [
        os.path.join(os.getcwd(), CONFIGURATION_FILE_NAME),  # Current directory
        DEFAULT_CONFIGURATION_FILE_PATH,  # User's home .data_exchange_agent folder
    ]

    # Return first path that exists
    for path in search_paths:
        if os.path.isfile(path):
            return path

    # If none found, return the default path (will fail with clear error message)
    return DEFAULT_CONFIGURATION_FILE_PATH


# For backwards compatibility - now dynamically finds config
CONFIGURATION_FILE_PATH = get_configuration_file_path()


def build_actual_results_folder_path(task_id: int | None = None) -> str:
    """
    Build the actual results folder path.

    Args:
        task_id (int | None): The task ID (optional)

    Returns:
        str: The actual results folder path

    """
    task_id_folder_name = _get_task_id_folder_name(task_id)
    timestamp_string = _get_timestamp_string()

    results_folder_path = os.path.join(
        ROOT_RESULTS_FOLDER_PATH,
        task_id_folder_name,
        timestamp_string,
    )
    return results_folder_path


def _get_task_id_folder_name(task_id: int | None) -> str:
    """
    Get the task ID folder name.

    Args:
        task_id (int | None): The task ID

    """
    return f"task_{task_id}" if task_id else "unknown_task_id"


def _get_timestamp_string() -> str:
    """Get the timestamp string."""
    now = datetime.now()
    milliseconds = now.microsecond // 1000
    timestamp_string = f"{now.strftime('%Y-%m-%d_%H-%M-%S')}_{milliseconds:03d}"
    return timestamp_string
