import logging
from typing import Any, List

from injector import Binder, Module, inject, singleton

from rep0st.db.post import Post, PostRepository, PostRepositoryModule
from rep0st.framework import app
from rep0st.framework.data.transaction import transactional
from rep0st.framework.execute import execute
from rep0st.pr0gramm.api import Pr0grammAPI, Pr0grammAPIModule
from rep0st.service.download_media_service import DownloadMediaService, DownloadMediaServiceModule

log = logging.getLogger(__name__)


class FixMediaFilesAndLinksJobModule(Module):

  def configure(self, binder: Binder):
    binder.install(PostRepositoryModule)
    binder.install(Pr0grammAPIModule)
    binder.install(DownloadMediaServiceModule)
    binder.bind(FixMediaFilesAndLinksJob)


@singleton
class FixMediaFilesAndLinksJob:
  api: Pr0grammAPI = None

  @inject
  def __init__(self, api: Pr0grammAPI, post_repository: PostRepository,
               download_media_service: DownloadMediaService):
    self.api = api
    self.post_repository = post_repository
    self.download_media_service = download_media_service

  @transactional()
  def fix_post(self, new_post: Post):
    old_post = self.post_repository.get_by_id(new_post.id).one()
    post = self.download_media_service.rename_media(old_post, new_post)
    post.thumb = new_post.thumb
    self.post_repository.persist(post)

  @execute()
  def fix_posts_job(self):
    for post in self.api.iterate_posts(start=0):
      try:
        log.info(f'Fixing post {post.id}')
        self.fix_post(post)
      except Exception:
        log.exception(f'Error handling post {post.id} for rename')


def modules() -> List[Any]:
  return [FixMediaFilesAndLinksJobModule]


if __name__ == "__main__":
  app.run(modules)

@@ -38,16 +38,39 @@
 , List%0A%0A
+from absl import flags%0A
 from inj
@@ -523,16 +523,182 @@
 ame__)%0A%0A
+FLAGS = flags.FLAGS%0Aflags.DEFINE_integer(%0A  'rep0st_fix_media_files_and_links_job_startid', None,%0A  'Start iterating posts from the pr0gramm at the given post id.')%0A%0A
 %0Aclass F
@@ -1586,16 +1586,159 @@
 (self):%0A
+    startid = 0%0A    if FLAGS.rep0st_fix_media_files_and_links_job_startid:%0A      startid = FLAGS.rep0st_fix_media_files_and_links_job_startid%0A%0A
     for 
@@ -1774,17 +1774,23 @@
 s(start=
-0
+startid
 ):%0A     

Add a flag to the fix media links job that allows the operation to be started at pr0gramm post ID.