"""실험: 옥탑방 내부(L05) 배경을 동서남북 4방향으로 생성.

인물 대신 점선 실루엣(최대 3명) 표시.
생성 후 frontend/public/experiment/ 에 N.png S.png W.png E.png 저장.

Usage:
    cd backend && python -m scripts.experiment_bg_angles
"""

import sys, os, time, pathlib

sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
os.environ.setdefault("RUNNING_SCRIPT", "1")

from app.core.config import settings
from app.modules.llm.gemini_image_client import GeminiImageClient

# ── L05 배경 설명 ──
LOCATION_DESC = (
    "A small, worn rooftop apartment interior in modern-day Korea. "
    "Compact living area with a tiny sunlit window, simple sink area, "
    "small table with chairs, old television, modest household furnishings, "
    "narrow space, lived-in and slightly aged walls and floor."
)

# ── 방향별 프롬프트 ──
DIRECTIONS = {
    "N": {
        "camera": "Camera facing the north wall (window side)",
        "view": "looking toward the small sunlit window and sink area, table on the right side",
    },
    "S": {
        "camera": "Camera facing the south wall (entrance side)",
        "view": "looking toward the entrance door and shoe rack area, television visible on the left",
    },
    "W": {
        "camera": "Camera facing the west wall",
        "view": "looking toward the kitchen sink counter and shelves, narrow corridor to bathroom",
    },
    "E": {
        "camera": "Camera facing the east wall",
        "view": "looking toward the old television and small bookshelf, window light coming from behind",
    },
}

SILHOUETTE_INSTRUCTION = (
    "CRITICAL INSTRUCTION: Do NOT draw any real human figures or faces. "
    "Instead, draw exactly 3 person-shaped DOTTED LINE silhouettes (outlines only, "
    "no fill, thin dashed/dotted stroke) standing naturally in the room. "
    "The silhouettes should be semi-transparent placeholders showing where "
    "actors would stand — like a stage blocking diagram. "
    "Each silhouette should be a different height (tall/medium/short) "
    "and positioned at different depths in the room. "
    "The silhouettes must be clearly visible but not dominant — "
    "the focus is the room environment."
)

STYLE = (
    "Photorealistic cinematic interior shot, "
    "warm natural lighting from the window, "
    "16:9 widescreen composition, film grain, "
    "shallow depth of field background, "
    "Korean residential aesthetic."
)


def build_prompt(direction: str, info: dict) -> str:
    return (
        f"{info['camera']}. {info['view']}.\n\n"
        f"SETTING: {LOCATION_DESC}\n\n"
        f"{SILHOUETTE_INSTRUCTION}\n\n"
        f"STYLE: {STYLE}"
    )


def main():
    out_dir = pathlib.Path(__file__).resolve().parent.parent.parent / "frontend" / "public" / "experiment"
    out_dir.mkdir(parents=True, exist_ok=True)

    client = GeminiImageClient(model=settings.gemini_image_model)
    client.set_context(step="experiment_bg_angles", operation_type="experiment")

    print(f"Model: {settings.gemini_image_model}")
    print(f"Output: {out_dir}")
    print()

    for direction, info in DIRECTIONS.items():
        prompt = build_prompt(direction, info)
        print(f"[{direction}] Generating... ", end="", flush=True)
        t0 = time.time()

        try:
            img_bytes, resp_ms = client.generate_image(
                prompt=prompt,
                aspect_ratio="16:9",
            )
            out_path = out_dir / f"{direction}.png"
            out_path.write_bytes(img_bytes)
            elapsed = time.time() - t0
            print(f"OK  {len(img_bytes)//1024}KB  {elapsed:.1f}s  → {out_path.name}")
        except Exception as e:
            print(f"FAIL: {e}")

    print()
    print("Done! Files at:")
    for d in DIRECTIONS:
        p = out_dir / f"{d}.png"
        if p.exists():
            print(f"  http://localhost:5173/experiment/{d}.png")


if __name__ == "__main__":
    main()
