"""Cloud Run entrypoint for the standalone Gremlin Deal Desk service."""

from __future__ import annotations

import os
from pathlib import Path
from typing import Any

from g_gremlin.autopilot.token_store import TokenStore

from .server import create_app


def _resolve_port(default: int = 8080) -> int:
    raw = str(os.getenv("PORT") or default).strip()
    try:
        return int(raw)
    except (TypeError, ValueError):
        return default


def _resolve_state_dir() -> Path:
    raw = str(os.getenv("G_GREMLIN_STATE_DIR") or "/tmp/g_gremlin_autopilot").strip()
    return Path(raw).expanduser().resolve()


def _seed_salesforce_runtime_auth(state_dir: Path) -> None:
    org_alias = str(os.getenv("G_GREMLIN_SFDC_ORG_ALIAS") or "").strip()
    if not org_alias:
        return

    payload: dict[str, Any] = {
        "org_alias": org_alias,
        "instance_url": str(os.getenv("G_GREMLIN_SFDC_INSTANCE_URL") or "").strip() or None,
        "org_id": str(os.getenv("G_GREMLIN_SFDC_ORG_ID") or "").strip() or None,
        "token_type": str(os.getenv("G_GREMLIN_SFDC_TOKEN_TYPE") or "").strip() or None,
        "access_token": str(os.getenv("G_GREMLIN_SFDC_ACCESS_TOKEN") or "").strip() or None,
        "refresh_token": str(os.getenv("G_GREMLIN_SFDC_REFRESH_TOKEN") or "").strip() or None,
        "client_id": str(os.getenv("G_GREMLIN_SFDC_CLIENT_ID") or "").strip() or None,
        "client_secret": str(os.getenv("G_GREMLIN_SFDC_CLIENT_SECRET") or "").strip() or None,
        "username": str(os.getenv("G_GREMLIN_SFDC_USERNAME") or "").strip() or None,
        "password": str(os.getenv("G_GREMLIN_SFDC_PASSWORD") or "").strip() or None,
        "security_token": str(os.getenv("G_GREMLIN_SFDC_SECURITY_TOKEN") or "").strip() or None,
    }
    api_version = str(os.getenv("G_GREMLIN_SALESFORCE_API_VERSION") or "").strip()
    if api_version:
        payload["api_version"] = api_version

    TokenStore(state_dir).save_tokens("salesforce", payload)

    access_token = str(payload.get("access_token") or "").strip()
    if access_token:
        import g_gremlin.sfdc as sfdc_helpers

        sfdc_helpers.set_configured_org(
            org_alias,
            instance_url=str(payload.get("instance_url") or "").strip() or None,
            access_token=access_token,
            refresh_token=str(payload.get("refresh_token") or "").strip() or None,
        )


# Cloud Run filesystem is ephemeral. Keep the pilot state tree under /tmp so
# the service can run as a single-instance pilot without extra infrastructure.
_STATE_DIR = _resolve_state_dir()
os.environ.setdefault("G_GREMLIN_STATE_DIR", str(_STATE_DIR))
os.environ.setdefault("G_GREMLIN_HOME", str(_STATE_DIR))
_seed_salesforce_runtime_auth(_STATE_DIR)


app = create_app(
    allow_remote=True,
    port=_resolve_port(),
    api_key=os.getenv("INTERNAL_API_KEY"),
)
