import os
import sys
from pathlib import Path
from dotenv import load_dotenv

# Carrega .env — procura em ordem de prioridade:
# 1. Diretorio do proprio script (mcp/.env)
# 2. ~/.fluig-mcp/.env (persistente, independente de cache npx)
# 3. Variaveis de ambiente ja definidas (Docker, etc.)
_script_dir = Path(__file__).resolve().parent
_env_local = _script_dir / ".env"
_env_home = Path.home() / ".fluig-mcp" / ".env"

if _env_local.exists():
    load_dotenv(_env_local)
    print(f"Config: .env carregado de {_env_local}", file=sys.stderr)
elif _env_home.exists():
    load_dotenv(_env_home)
    print(f"Config: .env carregado de {_env_home}", file=sys.stderr)
else:
    # Tenta carregar de variaveis de ambiente (Docker, CI, etc.)
    print(f"Config: .env nao encontrado em {_env_local} nem {_env_home} — usando variaveis de ambiente", file=sys.stderr)

FLUIG_SERVER = os.getenv("FLUIG_SERVER", "")
FLUIG_CONSUMER_KEY = os.getenv("FLUIG_CONSUMER_KEY", "")
FLUIG_CONSUMER_SECRET = os.getenv("FLUIG_CONSUMER_SECRET", "")
FLUIG_ACCESS_TOKEN = os.getenv("FLUIG_ACCESS_TOKEN", "")
FLUIG_TOKEN_SECRET = os.getenv("FLUIG_TOKEN_SECRET", "")
FLUIG_VERIFY_SSL = os.getenv("FLUIG_VERIFY_SSL", "true").lower() not in ("false", "0", "no")
# Controla se adiciona prefixo de modulo nas URLs (ex: /dataset, /process-management)
# Algumas versoes/configuracoes do Fluig nao usam esses prefixos
FLUIG_MODULE_PREFIX = os.getenv("FLUIG_MODULE_PREFIX", "true").lower() not in ("false", "0", "no")


def has_oauth_credentials() -> bool:
    return all([
        FLUIG_SERVER,
        FLUIG_CONSUMER_KEY,
        FLUIG_CONSUMER_SECRET,
        FLUIG_ACCESS_TOKEN,
        FLUIG_TOKEN_SECRET,
    ])
