#!/usr/bin/env python3
"""Replace Trae remote image URLs with local demo assets."""
from __future__ import annotations

import glob
import re
from pathlib import Path

ROOT = Path("/home/shiojima/Documents/trae_projects/shuzhi/src")

# Longer fragments first to avoid partial matches.
MAPPING = [
    (
        "realistic%20elderly%20chinese%20woman%20portrait%20warm%20smile%20soft%20golden%20lighting%20digital%20art",
        "avatars/woman-realistic-gold.jpg",
    ),
    (
        "realistic%20elderly%20chinese%20woman%20portrait%20warm%20expression%20soft%20golden%20lighting%20digital%20art",
        "avatars/woman-realistic-expr.jpg",
    ),
    (
        "elderly%20chinese%20woman%20portrait%20warm%20smile%20soft%20lighting",
        "avatars/woman-warm-soft.jpg",
    ),
    (
        "elderly%20chinese%20woman%20portrait%20warm%20smile",
        "avatars/woman-warm-smile.jpg",
    ),
    (
        "elderly%20chinese%20woman%20portrait%20grandmother%20warm%20kind",
        "avatars/woman-grandmother.jpg",
    ),
    (
        "elderly%20chinese%20woman%20portrait%20teacher%20glasses%20kind",
        "avatars/woman-teacher.jpg",
    ),
    (
        "middle%20aged%20chinese%20woman%20portrait%20professional%20business%20attire",
        "avatars/woman-business.jpg",
    ),
    (
        "middle%20aged%20chinese%20woman%20professional%20portrait",
        "avatars/woman-professional.jpg",
    ),
    (
        "young%20chinese%20woman%20portrait%20modern%20style",
        "avatars/woman-young.jpg",
    ),
    (
        "elderly%20chinese%20man%20portrait%20gentle%20expression%20traditional%20clothing",
        "avatars/man-traditional.jpg",
    ),
    (
        "elderly%20chinese%20man%20portrait%20kind%20expression",
        "avatars/man-kind.jpg",
    ),
    (
        "elderly%20chinese%20man%20portrait%20scholar%20traditional%20chinese%20style",
        "avatars/man-scholar.jpg",
    ),
    (
        "elderly%20chinese%20man%20portrait%20doctor%20white%20coat%20professional",
        "avatars/man-doctor.jpg",
    ),
    (
        "middle%20aged%20chinese%20man%20portrait%20engineer%20professional",
        "avatars/man-engineer.jpg",
    ),
    (
        "chinese%20family%20portrait%20traditional%20style%20warm%20lighting",
        "photos/family-traditional.jpg",
    ),
    (
        "family%20photo%20chinese%20family%20warm%20atmosphere",
        "photos/family-warm.jpg",
    ),
    (
        "elderly%20chinese%20woman%20cooking%20in%20kitchen%20warm%20atmosphere",
        "photos/cooking.jpg",
    ),
    (
        "elderly%20chinese%20woman%20gardening%20flowers%20sunny%20day",
        "photos/gardening.jpg",
    ),
    (
        "elderly%20chinese%20woman%20with%20grandchildren%20happy%20moment",
        "photos/grandchildren.jpg",
    ),
    (
        "elderly%20chinese%20woman%20traveling%20scenic%20spot",
        "photos/travel.jpg",
    ),
    (
        "elderly%20chinese%20woman%20celebrating%20birthday%20cake",
        "photos/birthday.jpg",
    ),
    (
        "serene%20memorial%20garden%20with%20soft%20golden%20light",
        "photos/garden-memorial.jpg",
    ),
]

URL_RE = re.compile(
    r"https://trae-api-cn\.mchost\.guru/api/ide/v1/text_to_image\?prompt=[^\"'\s>]+"
)
# Truncated / broken remnants from Trae export
BROKEN_RE = re.compile(r'<img\s+src="https://trae-api-cn\.m[^"]*')


def resolve_asset(url: str, depth: int) -> str | None:
    for frag, rel in MAPPING:
        if frag in url:
            return ("../" * depth) + "assets/" + rel
    return None


def process_file(path: Path) -> int:
    text = path.read_text(encoding="utf-8")
    orig = text
    count = 0
    # pages/ -> depth 1; components/x/ -> depth 2
    rel = path.relative_to(ROOT)
    depth = len(rel.parts) - 1

    def sub(m: re.Match[str]) -> str:
        nonlocal count
        mapped = resolve_asset(m.group(0), depth)
        if mapped is None:
            return m.group(0)
        count += 1
        return mapped

    text = URL_RE.sub(sub, text)

    def sub_broken(m: re.Match[str]) -> str:
        nonlocal count
        count += 1
        return f'<img src="{("../" * depth)}assets/photos/family-warm.jpg"'

    text = BROKEN_RE.sub(sub_broken, text)

    if text != orig:
        path.write_text(text, encoding="utf-8")
    return count


def main() -> None:
    total = 0
    for fp in glob.glob(str(ROOT / "**/*.html"), recursive=True):
        n = process_file(Path(fp))
        if n:
            print(f"updated {fp}: {n}")
            total += n
    print(f"total replacements: {total}")
    remain = []
    for fp in glob.glob(str(ROOT / "**/*.html"), recursive=True):
        t = Path(fp).read_text(encoding="utf-8")
        if "trae-api" in t:
            remain.append(fp)
    print("remaining trae-api refs:", remain)


if __name__ == "__main__":
    main()
