# -*- coding=UTF-8 -*-
# pyright: strict

from __future__ import annotations

import re

import os
import logging

_LOGGER = logging.getLogger(__name__)

_IMAGE_DIR = "_images"
_IMAGE_PATTERN = re.compile(r"_images/(.+\.(png|jpg))")


def iter_image_names():
    for dirpath, dirnames, filenames in os.walk("."):
        dirnames[:] = [
            i for i in dirnames if not (i.startswith(("_", ".", "scripts")))
        ]
        for i in filenames:
            if not i.endswith((".rst", ".md")):
                continue
            p = os.path.join(dirpath, i)
            _LOGGER.debug("read: %s", p)
            with open(p, encoding="utf-8") as f:
                for line in f:
                    for match in _IMAGE_PATTERN.finditer(line):
                        if match:
                            yield match.group(1)


def main():
    image_names = set(iter_image_names())
    for i in os.listdir(_IMAGE_DIR):
        if i in image_names:
            continue
        if not i.endswith((".png", ".jpg")):
            _LOGGER.warning("ignore file: %s", i)
            continue
        p = os.path.join(_IMAGE_DIR, i)
        print(p)
        os.unlink(p)


if __name__ == "__main__":
    logging.basicConfig(level=logging.DEBUG)
    main()
