"""Addon preferences + the effective API base.

Site resolution order: TB_SITE_URL env (a sandbox terminal launch) → the
preferences override (for a Dock-launched Blender pointed at a local sandbox)
→ the production default. The override is a URL, not a secret — the credential
itself never touches Blender preferences (they can be exported/synced).
"""

from __future__ import annotations

import os

import bpy

from ._core import config


class TBHubPreferences(bpy.types.AddonPreferences):
    # Must equal the module name Blender registered the addon under —
    # `three_blocks` legacy, `bl_ext.<repo>.three_blocks` as an extension.
    bl_idname = __package__

    site_override: bpy.props.StringProperty(
        name="Site override",
        description=(
            "API base for local testing (e.g. http://localhost:3000). "
            "Blank = threejs-blocks.com. TB_SITE_URL takes precedence when set"
        ),
        default="",
    )

    def draw(self, context):
        layout = self.layout
        layout.prop(self, "site_override")
        muted = layout.column()
        muted.enabled = False
        muted.label(text=f"Signing in against: {effective_site_url()}")
        muted.label(text="Credentials are stored in ~/.three-blocks/credentials.json (shared with the CLI).")


def effective_site_url() -> str:
    env = os.environ.get("TB_SITE_URL")
    if env:
        return env.rstrip("/")
    try:
        preferences = bpy.context.preferences.addons[__package__].preferences
        override = (preferences.site_override or "").strip()
        if override:
            return override.rstrip("/")
    except (AttributeError, KeyError):
        pass  # prefs not registered yet (headless import) — fall through
    return config.DEFAULT_SITE


def register():
    bpy.utils.register_class(TBHubPreferences)


def unregister():
    bpy.utils.unregister_class(TBHubPreferences)
