#!/usr/bin/env python3
"""Darkoza Node Agent 2.4.1 — explicit enrollment, account pairing, allowlisted, bounded distributed work with self-service revocation."""
from __future__ import annotations
import argparse
import hashlib
import json
import math
import os
import platform
import re
import secrets
import shutil
import signal
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

API = "https://darkoza.com/node-api"
VERSION = "2.4.1"
HEARTBEAT_INTERVAL = 30
POLL_INTERVAL = 2
MAX_SEGMENT_WIDTH = 100_000
MAX_PRIME_BOUND = 1_000_000_000
MAX_PI_SEGMENT_SAMPLES = 50_000
MAX_PI_BATCH_SEGMENTS = 5
MAX_PI_SEED = (1 << 32) - 1
MASK64 = (1 << 64) - 1
TASK_WALL_SECONDS = 8
STATE_DIR = Path(os.environ.get("DARKOZA_NODE_HOME", str(Path.home()/".local"/"share"/"darkoza-node")))
STATE_FILE = STATE_DIR / "identity.json"
OPT_IN_FILE = STATE_DIR / "compute-opt-in.json"


class FatalAgentError(Exception):
    pass


class TaskRejected(Exception):
    pass


def now_ms():
    return int(time.time() * 1000)


def memory_bytes():
    if sys.platform.startswith("linux"):
        try:
            for line in Path("/proc/meminfo").read_text().splitlines():
                if line.startswith("MemTotal:"):
                    return int(line.split()[1]) * 1024
        except (OSError, ValueError, IndexError):
            pass
    if sys.platform == "darwin":
        try:
            value = subprocess.check_output(
                ["sysctl", "-n", "hw.memsize"], text=True, timeout=3
            ).strip()
            return max(0, int(value))
        except (OSError, subprocess.SubprocessError, ValueError):
            pass
    return 0


def resources():
    return {
        "name": socket.gethostname()[:80],
        "platform": platform.system()[:24],
        "architecture": platform.machine()[:24],
        "cpu_count": max(1, int(os.cpu_count() or 1)),
        "memory_bytes": memory_bytes(),
        "agent_version": VERSION,
        "compute_opt_in": local_compute_opt_in(),
    }


def ensure_state_dir():
    STATE_DIR.mkdir(parents=True, exist_ok=True, mode=0o700)
    try:
        os.chmod(STATE_DIR, 0o700)
    except OSError:
        pass


def atomic_write(path: Path, payload: dict):
    ensure_state_dir()
    temp = path.with_suffix(path.suffix + ".tmp")
    temp.write_text(json.dumps(payload, separators=(",", ":")))
    os.chmod(temp, 0o600)
    temp.replace(path)


def load_identity():
    ensure_state_dir()
    if STATE_FILE.exists():
        try:
            state = json.loads(STATE_FILE.read_text())
            if (
                isinstance(state, dict)
                and isinstance(state.get("secret"), str)
                and len(state["secret"]) >= 40
                and isinstance(state.get("node_id"), str)
            ):
                return state
        except (OSError, json.JSONDecodeError):
            pass
    # New identities are created only by the explicit enrollment flow.
    raise FatalAgentError("Node identity is missing. Run the official join installer first.")


def local_compute_opt_in():
    try:
        data = json.loads(OPT_IN_FILE.read_text())
        return data.get("enabled") is True and data.get("policy") == "allowlisted-science-v2"
    except (OSError, json.JSONDecodeError, AttributeError):
        return False


def set_local_compute_opt_in(enabled: bool):
    if enabled:
        atomic_write(OPT_IN_FILE, {
            "enabled": True,
            "policy": "allowlisted-science-v2",
            "task_types": ["prime_count_segment", "monte_carlo_pi_segment", "monte_carlo_pi_batch_segment"],
            "max_segment_width": MAX_SEGMENT_WIDTH,
            "max_wall_seconds": TASK_WALL_SECONDS,
            "enabled_at": int(time.time()),
        })
        print("Local compute consent enabled for bounded prime-count and Monte Carlo pi tasks only.")
    else:
        try:
            OPT_IN_FILE.unlink()
        except FileNotFoundError:
            pass
        print("Local compute consent disabled. The agent will stop claiming new tasks.")


def request_json(path: str, payload: dict, secret: str | None = None):
    data = json.dumps(payload, separators=(",", ":")).encode()
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "User-Agent": "DarkozaNodeAgent/" + VERSION,
    }
    if secret:
        headers["Authorization"] = "Bearer " + secret
    req = urllib.request.Request(API + path, data=data, headers=headers, method="POST")
    try:
        with urllib.request.urlopen(req, timeout=15) as response:
            result = json.loads(response.read(8192))
            if not isinstance(result, dict):
                raise RuntimeError("invalid_registry_response")
            return result
    except urllib.error.HTTPError as exc:
        detail = exc.read(2048).decode("utf-8", "replace")
        if exc.code == 403:
            raise FatalAgentError("Node access was revoked by the registry.") from exc
        if exc.code in (409, 422):
            raise TaskRejected(f"task_rejected_http_{exc.code}: {detail[:200]}") from exc
        raise RuntimeError(f"registry_http_{exc.code}: {detail[:300]}") from exc
    except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
        raise RuntimeError(f"registry_unavailable: {exc}") from exc


def enroll():
    """Create a fresh quarantined node identity after an explicit local installer run."""
    ensure_state_dir()
    if STATE_FILE.exists():
        try:
            existing = json.loads(STATE_FILE.read_text())
            if isinstance(existing, dict) and isinstance(existing.get("node_id"), str) and isinstance(existing.get("secret"), str):
                print("This device already has a Darkoza node identity; enrollment was not repeated.")
                return 0
        except (OSError, json.JSONDecodeError):
            raise FatalAgentError("Existing node identity is unreadable; refusing to overwrite it.")
    secret = secrets.token_urlsafe(48)
    payload = {**resources(), "secret": secret}
    result = request_json("/register", payload)
    node_id = result.get("node_id")
    status = result.get("status")
    if not isinstance(node_id, str) or status not in ("quarantined", "approved"):
        raise RuntimeError("Registry did not return a valid quarantined node identity.")
    state = {
        "node_id": node_id,
        "secret": secret,
        "status": status,
        "compute_enabled": False,
        "permissions": result.get("permissions", ["resource_telemetry", "heartbeat"]),
        "created_at": int(time.time()),
    }
    atomic_write(STATE_FILE, state)
    print("Node identity registered successfully.")
    print("Registry status: " + status)
    print("Compute remains disabled. Account pairing and separate approval are required.")
    return 0


def heartbeat(state):
    result = request_json("/heartbeat", {
        "node_id": state["node_id"],
        **resources(),
    }, state["secret"])
    state["status"] = result.get("status", state.get("status", "quarantined"))
    state["compute_enabled"] = bool(result.get("compute_enabled", False))
    state["permissions"] = result.get("permissions", ["resource_telemetry", "heartbeat"])
    atomic_write(STATE_FILE, state)
    return result


def base_primes(limit: int):
    if limit < 2:
        return []
    sieve = bytearray(b"\x01") * (limit + 1)
    sieve[0:2] = b"\x00\x00"
    for value in range(2, math.isqrt(limit) + 1):
        if sieve[value]:
            start = value * value
            count = ((limit - start) // value) + 1
            sieve[start:limit + 1:value] = b"\x00" * count
    return [value for value in range(2, limit + 1) if sieve[value]]


def prime_count_segment(payload: dict):
    if not isinstance(payload, dict) or set(payload) != {"start", "end"}:
        raise TaskRejected("invalid_prime_count_payload")
    start, end = payload.get("start"), payload.get("end")
    if (
        isinstance(start, bool) or isinstance(end, bool)
        or not isinstance(start, int) or not isinstance(end, int)
        or start < 2 or end < start
        or end > MAX_PRIME_BOUND
        or end - start + 1 > MAX_SEGMENT_WIDTH
    ):
        raise TaskRejected("prime_count_bounds_rejected")

    width = end - start + 1
    segment = bytearray(b"\x01") * width
    for prime in base_primes(math.isqrt(end)):
        first = max(prime * prime, ((start + prime - 1) // prime) * prime)
        if first <= end:
            count = ((end - first) // prime) + 1
            segment[first - start:width:prime] = b"\x00" * count

    result_count = sum(segment)
    digest = hashlib.sha256(segment).hexdigest()
    return {
        "algorithm": "segmented-sieve-v1",
        "range_start": start,
        "range_end": end,
        "count": result_count,
        "bitmap_sha256": digest,
    }


def splitmix64(value: int):
    value = (value + 0x9E3779B97F4A7C15) & MASK64
    value = ((value ^ (value >> 30)) * 0xBF58476D1CE4E5B9) & MASK64
    value = ((value ^ (value >> 27)) * 0x94D049BB133111EB) & MASK64
    return value ^ (value >> 31)


def monte_carlo_pi_segment(payload: dict):
    if not isinstance(payload, dict) or set(payload) != {"sample_start", "sample_count", "seed"}:
        raise TaskRejected("invalid_monte_carlo_pi_payload")
    start, count, seed = payload.get("sample_start"), payload.get("sample_count"), payload.get("seed")
    if (
        isinstance(start, bool) or not isinstance(start, int) or start < 0
        or isinstance(count, bool) or not isinstance(count, int)
        or count < 1 or count > MAX_PI_SEGMENT_SAMPLES
        or isinstance(seed, bool) or not isinstance(seed, int)
        or seed < 0 or seed > MAX_PI_SEED
        or start + count > 100_000_000
    ):
        raise TaskRejected("monte_carlo_pi_bounds_rejected")
    bitmap = bytearray((count + 7) // 8)
    inside = 0
    radius_squared = 1 << 64
    for index in range(count):
        sample_index = start + index
        counter = (seed << 32) ^ (sample_index * 2)
        x_value = splitmix64(counter)
        y_value = splitmix64(counter + 1)
        x = x_value >> 32
        y = y_value >> 32
        if x * x + y * y <= radius_squared:
            inside += 1
            bitmap[index >> 3] |= 1 << (index & 7)
    return {
        "algorithm": "monte-carlo-pi-xorshift64star-v1",
        "sample_start": start,
        "sample_count": count,
        "seed": seed,
        "inside": inside,
        "bitmap_sha256": hashlib.sha256(bitmap).hexdigest(),
    }


def monte_carlo_pi_batch_segment(payload: dict):
    if not isinstance(payload, dict) or set(payload) != {"segments"}:
        raise TaskRejected("invalid_monte_carlo_pi_batch_payload")
    segments = payload.get("segments")
    if not isinstance(segments, list) or not 1 <= len(segments) <= MAX_PI_BATCH_SEGMENTS:
        raise TaskRejected("monte_carlo_pi_batch_size_rejected")
    results = [monte_carlo_pi_segment(segment) for segment in segments]
    return {
        "algorithm": "monte-carlo-pi-batch-v1",
        "segments": results,
    }


def execute_allowlisted_task(task: dict):
    if not isinstance(task, dict):
        raise TaskRejected("invalid_task")
    kind = task.get("kind")
    payload = task.get("payload")
    if kind == "prime_count_segment":
        operation = lambda: prime_count_segment(payload)
    elif kind == "monte_carlo_pi_segment":
        operation = lambda: monte_carlo_pi_segment(payload)
    elif kind == "monte_carlo_pi_batch_segment":
        operation = lambda: monte_carlo_pi_batch_segment(payload)
    else:
        raise TaskRejected("task_kind_not_allowlisted")
    previous = signal.getsignal(signal.SIGALRM)
    def timeout_handler(signum, frame):
        raise TimeoutError("task_wall_time_exceeded")
    signal.signal(signal.SIGALRM, timeout_handler)
    if hasattr(signal, "setitimer"):
        signal.setitimer(signal.ITIMER_REAL, TASK_WALL_SECONDS)
    else:
        signal.alarm(TASK_WALL_SECONDS)
    try:
        return operation()
    finally:
        if hasattr(signal, "setitimer"):
            signal.setitimer(signal.ITIMER_REAL, 0)
        else:
            signal.alarm(0)
        signal.signal(signal.SIGALRM, previous)


def claim_task(state):
    return request_json("/tasks/claim", {
        "node_id": state["node_id"],
        "agent_version": VERSION,
    }, state["secret"])


def submit_result(state, task, result=None, error=None):
    body = {
        "node_id": state["node_id"],
        "task_id": task.get("task_id"),
    }
    if result is not None:
        body["result"] = result
    if error:
        body["error"] = str(error)[:240]
    return request_json("/tasks/result", body, state["secret"])


def process_one_task(state):
    task = claim_task(state)
    if not task.get("task"):
        return False
    work = task["task"]
    started = now_ms()
    try:
        result = execute_allowlisted_task(work)
        result["worker_version"] = VERSION
        result["elapsed_ms"] = max(0, now_ms() - started)
        acknowledgement = submit_result(state, work, result=result)
        print(json.dumps({
            "task_id": work.get("task_id"),
            "job_id": work.get("job_id"),
            "status": acknowledgement.get("status"),
            "chunk_verified": acknowledgement.get("chunk_verified"),
        }, separators=(",", ":")), flush=True)
    except TaskRejected as exc:
        submit_result(state, work, error=str(exc))
        print(f"Rejected task {work.get('task_id')}: {exc}", file=sys.stderr, flush=True)
    except Exception as exc:
        try:
            submit_result(state, work, error=type(exc).__name__)
        except Exception:
            pass
        print(f"Task failed ({work.get('task_id')}): {type(exc).__name__}", file=sys.stderr, flush=True)
    return True


def run_once():
    state = load_identity()
    status = heartbeat(state)
    task_processed = False
    if status.get("compute_enabled") and local_compute_opt_in():
        task_processed = process_one_task(state)
    print(json.dumps({
        "node_id": state["node_id"],
        "status": state.get("status"),
        "compute_opt_in": local_compute_opt_in(),
        "compute_enabled": bool(status.get("compute_enabled")),
        "task_processed": task_processed,
        "permissions": status.get("permissions"),
    }, ensure_ascii=False), flush=True)


def daemon():
    try:
        os.nice(10)
    except (AttributeError, OSError):
        pass
    state = load_identity()
    next_heartbeat = 0.0
    compute_enabled = False
    while True:
        now = time.monotonic()
        try:
            if now >= next_heartbeat:
                status = heartbeat(state)
                compute_enabled = bool(status.get("compute_enabled"))
                next_heartbeat = time.monotonic() + HEARTBEAT_INTERVAL
                print(json.dumps({
                    "node_id": state["node_id"],
                    "status": state.get("status"),
                    "compute_opt_in": local_compute_opt_in(),
                    "compute_enabled": compute_enabled,
                }, separators=(",", ":")), flush=True)
            if compute_enabled and local_compute_opt_in():
                if process_one_task(state):
                    continue
            time.sleep(POLL_INTERVAL if compute_enabled else HEARTBEAT_INTERVAL)
        except FatalAgentError as exc:
            print(str(exc), file=sys.stderr, flush=True)
            return 3
        except Exception as exc:
            print(f"Darkoza node agent cycle failed: {type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
            time.sleep(HEARTBEAT_INTERVAL)


def pair_with_account(code: str) -> int:
    if not re.fullmatch(r"[A-Za-z0-9_-]{40,64}", code):
        print("Invalid pairing code format. Generate a new code from your signed-in Darkoza account.", file=sys.stderr)
        return 2
    try:
        state = load_identity()
        result = request_json("/pair/claim", {"node_id": state["node_id"], "code": code}, state["secret"])
        if result.get("linked") is not True or result.get("status") != "linked":
            raise RuntimeError("Darkoza did not confirm account ownership linking.")
        print("This node is now linked to the signed-in Darkoza account.")
        print("Account identity and email are not stored on this device or exposed by the public registry.")
        print("Compute permission remains governed by the existing local opt-in and Darkoza approval.")
        return 0
    except (FatalAgentError, TaskRejected, RuntimeError) as exc:
        print("Node account linking failed: " + str(exc), file=sys.stderr)
        return 2


def disconnect():
    state = load_identity()
    response = request_json("/revoke", {"node_id": state["node_id"]}, state["secret"])
    if response.get("revoked") is not True:
        raise RuntimeError("Darkoza did not confirm node revocation.")

    system = platform.system()
    if system == "Darwin":
        domain = f"gui/{os.getuid()}"
        target = f"{domain}/com.darkoza.node"
        plist = Path.home() / "Library" / "LaunchAgents" / "com.darkoza.node.plist"
        loaded = subprocess.run(
            ["launchctl", "print", target],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=8,
        ).returncode == 0
        if loaded and plist.exists():
            stopped = subprocess.run(
                ["launchctl", "bootout", domain, str(plist)],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=10,
            )
            if stopped.returncode != 0:
                raise RuntimeError("Node was revoked remotely, but its LaunchAgent could not be stopped. Run: launchctl bootout " + domain + " " + str(plist))
        subprocess.run(
            ["launchctl", "disable", target],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=8,
        )
        try:
            plist.unlink()
        except FileNotFoundError:
            pass
        log_file = Path.home() / "Library" / "Logs" / "darkoza-node.log"
        try:
            log_file.unlink()
        except FileNotFoundError:
            pass
    elif system == "Linux":
        unit = Path.home() / ".config" / "systemd" / "user" / "darkoza-node.service"
        if unit.exists():
            stopped = subprocess.run(
                ["systemctl", "--user", "disable", "--now", "darkoza-node.service"],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=20,
            )
            if stopped.returncode != 0:
                raise RuntimeError("Node was revoked remotely, but its user service could not be stopped. Run: systemctl --user disable --now darkoza-node.service")
            active = subprocess.run(
                ["systemctl", "--user", "is-active", "--quiet", "darkoza-node.service"],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=8,
            )
            if active.returncode == 0:
                raise RuntimeError("Node was revoked remotely, but its user service is still active. Stop it manually.")
            try:
                unit.unlink()
            except FileNotFoundError:
                pass
            subprocess.run(
                ["systemctl", "--user", "daemon-reload"],
                stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False, timeout=8,
            )
    else:
        raise RuntimeError("Automatic local removal is supported on macOS and Linux only.")

    if STATE_DIR.exists():
        shutil.rmtree(STATE_DIR)
    print("Node revoked on the Darkoza registry.")
    print("Background service disabled; local node identity and compute opt-in removed.")


def main():
    parser = argparse.ArgumentParser(description="Darkoza node agent")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("--enroll", action="store_true", help="explicitly register this device as a quarantined node")
    group.add_argument("--once", action="store_true", help="send one heartbeat and optionally run one allowed task")
    group.add_argument("--daemon", action="store_true", help="send heartbeats and poll the allowlisted task queue")
    group.add_argument("--status", action="store_true", help="show local node status")
    group.add_argument("--enable-compute", action="store_true", help="locally opt in to bounded allowlisted tasks")
    group.add_argument("--disable-compute", action="store_true", help="locally stop claiming compute tasks")
    group.add_argument("--disconnect", action="store_true", help="revoke this node and remove its local service and identity")
    group.add_argument("--pair", metavar="ONE_TIME_CODE", help="link this registered node to the signed-in Darkoza account using a one-time code")
    args = parser.parse_args()
    if args.enroll:
        return enroll()
    if args.pair:
        return pair_with_account(args.pair)
    if args.disconnect:
        disconnect()
        return 0
    if args.enable_compute:
        set_local_compute_opt_in(True)
        return 0
    if args.disable_compute:
        set_local_compute_opt_in(False)
        return 0
    if args.status:
        state = load_identity()
        print(json.dumps({
            "node_id": state.get("node_id"),
            "status": state.get("status", "unknown"),
            "compute_opt_in": local_compute_opt_in(),
            "compute_enabled": bool(state.get("compute_enabled", False)),
        }, ensure_ascii=False))
        return 0
    if args.once:
        run_once()
        return 0
    daemon()
    return 0


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except KeyboardInterrupt:
        raise SystemExit(0)
