"""
Shared helpers va hang so cho CLI (echo co lock, image_src, ensure playwright).
"""
from __future__ import annotations

import subprocess
import sys
import threading

import click

from ..constants import API_BASE_URL

_LINE = "─" * 56
_BOLD = "=" * 56


def ensure_playwright_browsers() -> None:
    """Cai Playwright Chromium tu dong neu chua co."""
    from playwright.sync_api import sync_playwright
    try:
        with sync_playwright() as pw:
            pw.chromium.launch(headless=True).close()
    except Exception:
        click.echo("Cai dat Playwright browsers (chi can 1 lan)...")
        subprocess.run(
            [sys.executable, "-m", "playwright", "install", "chromium"],
            check=True,
        )


def echo(lock: threading.Lock, msg: str) -> None:
    with lock:
        click.echo(msg)


def image_src(img_field: str | None) -> str | None:
    if not img_field:
        return None
    return f"{API_BASE_URL.rstrip('/')}/{img_field.lstrip('/')}"
