"""Dark Factory — ADW ZTE Engine. Ships via signed factory action endpoint."""
import hashlib
import hmac
import json
import logging
import os
import subprocess
import time
import urllib.error
import urllib.request
import uuid
from datetime import datetime

DEPLOY_URL = os.environ.get("DEPLOY_URL", "http://localhost:8099/deploy")
DEPLOY_TOKEN = os.environ.get("DEPLOY_TOKEN", "factory-deploy-token-2026")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(name)s] %(message)s")
log = logging.getLogger("dark-factory")


def signed_payload(action, target, actor="dark_factory", payload_hash="none"):
    data = {
        "timestamp": int(time.time()),
        "nonce": hashlib.sha256(f"{time.time()}:{target}:{action}".encode()).hexdigest()[:16],
        "actor": actor,
        "action": action,
        "target": target,
        "payload_hash": payload_hash,
    }
    body = json.dumps(data, sort_keys=True, separators=(",", ":")).encode()
    data["signature"] = hmac.new(DEPLOY_TOKEN.encode(), body, hashlib.sha256).hexdigest()
    return data


def post_deploy(payload):
    req = urllib.request.Request(
        DEPLOY_URL,
        data=json.dumps(payload).encode(),
        headers={"Authorization": f"Bearer {DEPLOY_TOKEN}", "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(req, timeout=15) as r:
            return {"exit": 0, "stdout": r.read().decode()[:200], "stderr": ""}
    except urllib.error.HTTPError as e:
        return {"exit": e.code, "stdout": e.read().decode()[:200], "stderr": ""}
    except Exception as e:
        return {"error": str(e)}


class DarkFactory:
    def __init__(self, issue=0, title="", body="", zte=True):
        self.id = f"df-{int(datetime.now().timestamp())}-{uuid.uuid4().hex[:4]}"
        self.issue = issue
        self.title = title
        self.body = body
        self.zte = zte

    def ssh(self, cmd):
        return subprocess.run(
            ["ssh", "-i", os.path.expanduser("~/.ssh/id_ed25519"), "-p", "2222",
             "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=10",
             "goku@77.42.112.29", cmd],
            capture_output=True, text=True, timeout=30,
        )

    def run_phase(self, name):
        log.info(f"Phase: {name}")
        return {"phase": name, "status": "ok"}

    def ship(self):
        payload_hash = hashlib.sha256(f"{self.id}:{self.issue}:{self.title}".encode()).hexdigest()[:16]
        return post_deploy(signed_payload("patch_skill_from_pr", self.id, payload_hash=payload_hash))

    def run(self):
        phases = [self.run_phase(p) for p in ["plan", "build", "test", "review", "document", "ship"]]
        all_ok = all(p["status"] == "ok" for p in phases)
        ship_result = self.ship() if all_ok else None
        log.info(f"Dark Factory {self.id} | Issue #{self.issue} | Shipped: {all_ok}")
        return {
            "id": self.id, "issue": self.issue, "title": self.title,
            "zte": self.zte, "phases": phases, "shipped": all_ok,
            "ship_response": ship_result, "status": "complete",
        }


if __name__ == "__main__":
    import argparse
    a = argparse.ArgumentParser(description="Dark Factory ZTE Engine")
    a.add_argument("--issue", type=int, default=0, help="GitHub issue number")
    a.add_argument("--title", default="Dark Factory build", help="Issue title")
    a.add_argument("--body", default="", help="Issue body")
    a.add_argument("--zte", action="store_true", default=True, help="Enable ZTE auto-ship")
    args = a.parse_args()

    df = DarkFactory(issue=args.issue, title=args.title, body=args.body, zte=args.zte)
    result = df.run()
    print(json.dumps(result, indent=2))

    if result["shipped"]:
        log.info(f"✅ Dark Factory {result['id']} shipped successfully")
    else:
        log.warning(f"❌ Dark Factory {result['id']} failed")
