"""
Legacy path mapper for assets generated by the 8502 runtime (/root/video-flow).

Problem:
- Postgres `scene_assets.local_path` may contain paths like `/root/video-flow/temp/...`
  which are not visible inside docker containers running 8503 stack.

Solution:
- Mount host directories into containers (e.g. /legacy/temp, /legacy/output)
- Map legacy host paths -> container paths, and produce static URLs accordingly.
"""

from __future__ import annotations

import os
from pathlib import Path
from typing import Optional, Tuple


LEGACY_HOST_TEMP_PREFIX = "/root/video-flow/temp/"
LEGACY_HOST_OUTPUT_PREFIX = "/root/video-flow/output/"

# Container mount points (see docker-compose.yml)
LEGACY_CONTAINER_TEMP_DIR = "/legacy/temp"
LEGACY_CONTAINER_OUTPUT_DIR = "/legacy/output"

LEGACY_STATIC_TEMP_PREFIX = "/static/legacy-temp/"
LEGACY_STATIC_OUTPUT_PREFIX = "/static/legacy-output/"


def map_legacy_local_path(local_path: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
    """
    Returns: (container_visible_path, static_url)
    - If local_path exists as-is, returns (local_path, None)
    - If it's a legacy host path, rewrite to container mount and provide URL
    - If unknown, returns (local_path, None)
    """
    if not local_path:
        return None, None

    # If container can see it already, keep
    if os.path.exists(local_path):
        return local_path, None

    # Legacy host -> container mapping by basename
    if local_path.startswith(LEGACY_HOST_TEMP_PREFIX):
        name = Path(local_path).name
        container_path = str(Path(LEGACY_CONTAINER_TEMP_DIR) / name)
        url = f"{LEGACY_STATIC_TEMP_PREFIX}{name}"
        return container_path, url

    if local_path.startswith(LEGACY_HOST_OUTPUT_PREFIX):
        name = Path(local_path).name
        container_path = str(Path(LEGACY_CONTAINER_OUTPUT_DIR) / name)
        url = f"{LEGACY_STATIC_OUTPUT_PREFIX}{name}"
        return container_path, url

    # Unknown path: keep as-is
    return local_path, None







