from __future__ import annotations

import os
from dataclasses import dataclass
from typing import Mapping

from app_config import load_local_env, save_local_env
from security import SecretVault


def environment_credentials(environment: Mapping[str, str]) -> dict[str, str]:
    return {
        "tushare_token": str(environment.get("TUSHARE_TOKEN") or "").strip(),
        "ifind_refresh_token": str(environment.get("IFIND_REFRESH_TOKEN") or "").strip(),
        "ifind_access_token": str(environment.get("IFIND_ACCESS_TOKEN") or "").strip(),
        "platform_llm_primary_api_key": str(
            environment.get("LLM_PRIMARY_API_KEY") or environment.get("LLM_API_KEY") or ""
        ).strip(),
        "platform_llm_primary_base_url": str(
            environment.get("LLM_PRIMARY_BASE_URL")
            or environment.get("LLM_BASE_URL")
            or "https://api.openai.com/v1"
        ).strip(),
        "platform_llm_primary_model": str(
            environment.get("LLM_PRIMARY_MODEL") or environment.get("LLM_MODEL") or ""
        ).strip(),
        "platform_llm_fallback_api_key": str(
            environment.get("LLM_FALLBACK_API_KEY") or ""
        ).strip(),
        "platform_llm_fallback_base_url": str(
            environment.get("LLM_FALLBACK_BASE_URL") or ""
        ).strip(),
        "platform_llm_fallback_model": str(
            environment.get("LLM_FALLBACK_MODEL") or ""
        ).strip(),
    }


@dataclass(frozen=True)
class RuntimeSettings:
    encryption_key: str
    initial_credentials: dict[str, str]


def load_runtime_settings() -> RuntimeSettings:
    load_local_env()
    encryption_key = os.environ.get("APP_ENCRYPTION_KEY", "").strip()
    if not encryption_key:
        encryption_key = SecretVault.generate_key()
        save_local_env({"APP_ENCRYPTION_KEY": encryption_key})
        os.environ["APP_ENCRYPTION_KEY"] = encryption_key
    return RuntimeSettings(
        encryption_key=encryption_key,
        initial_credentials=environment_credentials(os.environ),
    )
