import subprocess
import os
import sys
from datetime import datetime

DOCKERFILES = [
    'frontend/Dockerfile.dev',
    'landing-page/Dockerfile.dev',
    'server/Dockerfile.dev',
    'server/Dockerfile.pgvector',
    'server/Dockerfile.kubectl',
]

def get_path_modification_time(path):
    try:
        return datetime.fromtimestamp(os.path.getmtime(path))
    except OSError:
        return None

LAST_BUILD_TIME_PATH = '.docker-compose-last-build'

def touch(path):
    if os.path.exists(path):
        os.utime(path, None)
    else:
        open(path, 'a').close()

def main():
    args = ['docker', 'compose'] + sys.argv[1:]
    if 'up' in args:
        last_build_time = get_path_modification_time(LAST_BUILD_TIME_PATH)
        needs_rebuild = last_build_time is None
        if not needs_rebuild:
            for dockerfile in DOCKERFILES:
                file_time = get_path_modification_time(dockerfile)
                if file_time is None or file_time > last_build_time:
                    needs_rebuild = True
        if needs_rebuild:
            res = subprocess.run(["docker", "compose", "build"])
            if res.returncode == 0:
                touch(LAST_BUILD_TIME_PATH)
            args += ['--build']
    os.execvp("docker", args)

if __name__ == '__main__':
    main()
