import json
import docker
from flask import Flask, jsonify

# 兼容新旧版本
try:
    cli = docker.DockerClient(base_url='unix:///var/run/docker.sock')
except AttributeError:
    cli = docker.Client(base_url='unix:///var/run/docker.sock')

app = Flask(__name__)

# 容器列表
@app.route("/list")
def api_list():
    arr = []
    for c in cli.containers.list(all=True):
        img_name = c.image.tags[0] if c.image.tags else ""
        arr.append({
            "id": c.short_id,
            "full_id": c.id,
            "name": c.name,
            "image": img_name,
            "status": c.status,
            "ports": str(c.ports)
        })
    return jsonify({"code":0,"msg":"success","list":arr})

# 镜像列表
@app.route("/image_list")
def api_image_list():
    arr = []
    for img in cli.images.list():
        if not img.tags:
            continue
        full_tag = img.tags[0]
        repo, tag = full_tag.split(":", 1)
        size_mb = round(img.attrs["Size"] / 1024 / 1024, 1)
        arr.append({
            "repo": repo,
            "tag": tag,
            "id": img.short_id,
            "full_id": img.id,
            "size": f"{size_mb}MB",
            "created": img.attrs["Created"]
        })
    return jsonify({"code":0,"msg":"success","list":arr})

# 重启容器
@app.route("/restart/<cid>")
def api_restart(cid):
    try:
        cli.containers.get(cid).restart()
        return jsonify({"code":0,"msg":"容器已重启"})
    except Exception as e:
        return jsonify({"code":500,"msg":str(e)})

# 停止容器
@app.route("/stop/<cid>")
def api_stop(cid):
    try:
        cli.containers.get(cid).stop()
        return jsonify({"code":0,"msg":"容器已停止"})
    except Exception as e:
        return jsonify({"code":500,"msg":str(e)})

# 删除容器
@app.route("/rm/<cid>")
def api_rm(cid):
    try:
        cli.containers.get(cid).remove(force=True)
        return jsonify({"code":0,"msg":"容器已强制删除"})
    except Exception as e:
        return jsonify({"code":500,"msg":str(e)})

# 容器日志
@app.route("/logs/<cid>/<int:tail_lines>")
def api_logs(cid, tail_lines):
    try:
        log_bytes = cli.containers.get(cid).logs(tail=tail_lines)
        log_str = log_bytes.decode("utf-8", errors="ignore")
        return jsonify({"code":0,"msg":"success","data":log_str})
    except Exception as e:
        return jsonify({"code":500,"msg":str(e),"data":""})

# 网络信息
@app.route("/network/<cid>")
def api_network(cid):
    try:
        info = cli.containers.get(cid).attrs["NetworkSettings"]["Networks"]
        return jsonify({"code":0,"msg":"success","data":info})
    except Exception as e:
        return jsonify({"code":500,"msg":str(e),"data":""})

@app.route("/")
def index():
    return jsonify({"code":400,"msg":"无效操作","list":[],"data":""})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8090, debug=False)
