from sqlalchemy.ext.asyncio import AsyncSession

from app.config import get_settings
from app.models.oem import Oem
from app.schemas.oem_public import OemPublicBrandingOut


def _image_url(image_path: str | None, base_url: str) -> str | None:
    if not image_path or not image_path.strip():
        return None
    path = image_path.strip().replace("\\", "/").lstrip("/")
    if path.startswith("http://") or path.startswith("https://"):
        return path
    if not path.startswith("images/"):
        path = f"images/{path.removeprefix('images/')}"
    return f"{base_url.rstrip('/')}/{path}"


async def get_oem_public_branding(db: AsyncSession, oem_id: int) -> OemPublicBrandingOut:
    settings = get_settings()
    base_url = settings.api_public_base.rstrip("/")
    oem = await db.get(Oem, oem_id)
    if oem is None:
        return OemPublicBrandingOut(
            oem_id=oem_id,
            software_name="",
            logo_url=None,
            wechat=None,
            wechat_qrcode_url=None,
        )

    return OemPublicBrandingOut(
        oem_id=oem.id,
        software_name=oem.software_name or "",
        logo_url=_image_url(oem.logo_path, base_url),
        wechat=oem.wechat,
        wechat_qrcode_url=_image_url(oem.wechat_qrcode, base_url),
    )
