#!/usr/bin/env python3
# cleat: {"name":"Docker Containers","keyword":"docker","icon":"shippingbox","subtitle":"Inspect containers · explicitly start or stop the selected container","version":"2.0.0","requires":["python3","docker"],"examples":["docker ","docker postgres"],"emptyMessage":"No matching containers. Try another name or create a container in Docker."}
import json, subprocess, sys

def docker(*args):
    p=subprocess.run(['docker',*args],capture_output=True,text=True)
    if p.returncode: raise ValueError(p.stderr.strip() or 'Docker daemon unavailable. Start Docker and retry.')
    return p.stdout

def main():
    if len(sys.argv)>1 and sys.argv[1]=='--run':
        request=json.loads(sys.argv[2]); state=docker('inspect','-f','{{.State.Status}}',request['id']).strip()
        if state!=request['state']: raise ValueError('Container state changed. Refresh the list before acting.')
        action=request['action']
        if action not in ('start','stop'): raise ValueError('Unsupported container action')
        docker(action,request['id']); return
    query=(sys.argv[1] if len(sys.argv)>1 else '').casefold()
    rows=[json.loads(line) for line in docker('ps','-a','--no-trunc','--format','{{json .}}').splitlines() if line.strip()]
    for row in sorted(rows,key=lambda r:(r['State']!='running',r['Names'])):
        if query and query not in (row['Names']+' '+row['Image']).casefold(): continue
        state=row['State']; action='stop' if state=='running' else 'start'
        print(json.dumps({'id':row['ID'],'title':row['Names'],'subtitle':row['Image']+' · '+state+' · '+row.get('Ports',''),'arg':json.dumps({'id':row['ID'],'state':state,'action':action}),'icon':'shippingbox','actionLabel':action.title()+' Container'}))
if __name__=='__main__':
    try: main()
    except (OSError,ValueError,KeyError) as error:
        print(str(error),file=sys.stderr); sys.exit(1)
