"""Canonical shop_code resolution for Shopify attribute registry rows."""

from __future__ import annotations

from typing import List, Optional

from sqlalchemy import select
from sqlalchemy.orm import Session

from db.models import ShopifyConnection
from settings import load_shopify_config
from shopify.connections import get_active_connection


def resolve_shopify_connection(
    session: Session,
    *,
    connection_id: Optional[int] = None,
    native_connection_id: Optional[int] = None,
    shop_code: Optional[str] = None,
) -> Optional[ShopifyConnection]:
    """Resolve the Shopify connection row used for registry + API calls."""
    if native_connection_id is not None:
        row = session.get(ShopifyConnection, native_connection_id)
        if row is not None:
            return row
    if connection_id is not None:
        from db.compat_connections import decode_compat_connection_id

        channel_type, native_id = decode_compat_connection_id(connection_id)
        if channel_type == "shopify":
            row = session.get(ShopifyConnection, native_id)
            if row is not None:
                return row
    if shop_code:
        row = get_active_connection(session, shop_code=shop_code)
        if row is not None:
            return row
        row = session.scalar(
            select(ShopifyConnection).where(ShopifyConnection.shop_domain == shop_code).limit(1)
        )
        if row is not None:
            return row
    row = get_active_connection(session)
    if row is not None:
        return row
    cfg = load_shopify_config()
    if cfg.shop_domain:
        return session.scalar(
            select(ShopifyConnection).where(ShopifyConnection.shop_domain == cfg.shop_domain).limit(1)
        )
    return None


def resolve_registry_shop_code(
    session: Session,
    *,
    connection: Optional[ShopifyConnection] = None,
    shop_code: Optional[str] = None,
) -> str:
    """Return the single canonical registry shop_code for a store (never shop_domain)."""
    if connection is not None:
        return str(connection.shop_code).strip()
    resolved = resolve_shopify_connection(session, shop_code=shop_code)
    if resolved is not None:
        return str(resolved.shop_code).strip()
    explicit = str(shop_code or "").strip()
    if explicit:
        return explicit
    cfg = load_shopify_config()
    if cfg.shop_code and cfg.shop_code != cfg.shop_domain:
        return cfg.shop_code
    # ENV fallback may equal domain; callers should prefer a DB connection row.
    return str(cfg.shop_code or cfg.shop_domain or "").strip()


def alternate_registry_shop_codes(
    *,
    connection: Optional[ShopifyConnection] = None,
    canonical_shop_code: str,
) -> List[str]:
    """Legacy shop_code aliases that should be merged into the canonical key."""
    canonical = str(canonical_shop_code or "").strip()
    alternates: List[str] = []
    if connection is not None:
        domain = str(connection.shop_domain or "").strip()
        if domain and domain != canonical:
            alternates.append(domain)
    cfg = load_shopify_config()
    cfg_code = str(cfg.shop_code or "").strip()
    cfg_domain = str(cfg.shop_domain or "").strip()
    for candidate in (cfg_code, cfg_domain):
        if candidate and candidate != canonical and candidate not in alternates:
            alternates.append(candidate)
    return alternates
