# /apps/aroflo_connector_app/ui_automation/core/artifacts.py
from __future__ import annotations

import time
from pathlib import Path

from playwright.sync_api import Page

from .paths import STATE_DIR, ARTIFACTS_DIR


def _now_tag() -> str:
    return time.strftime("%Y%m%d-%H%M%S")


def _ensure_dirs() -> None:
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    ARTIFACTS_DIR.mkdir(parents=True, exist_ok=True)


def _write_html_dump(page: Page, path: Path) -> None:
    """
    Dump HTML. Si falla, escribe un archivo con el error para no quedar a ciegas.
    """
    try:
        html = page.content()
        path.write_text(html, encoding="utf-8")
    except Exception as e:
        path.write_text(
            f"<!-- ERROR dumping page.content(): {type(e).__name__}: {e} -->\n",
            encoding="utf-8",
        )


def shot(page: Page, run_dir: Path, name: str) -> None:
    """
    Screenshot + HTML dump.
    """
    # 1) Screenshot
    try:
        page.screenshot(
            path=str(run_dir / f"{name}.png"),
            full_page=True,
            animations="disabled",
        )
    except Exception:
        pass

    # 2) HTML (siempre)
    _write_html_dump(page, run_dir / f"{name}.html")


def create_run_dir(cfg, prefix: str) -> Path:
    """
    Crea carpeta de artifacts para una corrida.
    Usa cfg.artifacts_dir si existe; si no, ARTIFACTS_DIR por defecto.
    """
    _ensure_dirs()

    base = getattr(cfg, "artifacts_dir", None)
    base_dir = Path(base) if base else ARTIFACTS_DIR

    run_dir = base_dir / f"{prefix}-{_now_tag()}"
    run_dir.mkdir(parents=True, exist_ok=True)
    return run_dir
