###
# Warranty & Liability
# To the extent permitted by applicable law and unless explicitly
# otherwise agreed upon, XLOG Technologies AG makes no warranties
# regarding the provided information. XLOG Technologies AG assumes
# no liability that any problems might be solved with the information
# provided by XLOG Technologies AG.
#
# Rights & License
# All industrial property rights regarding the information - copyright
# and patent rights in particular - are the sole property of XLOG
# Technologies AG. If the company was not the originator of some
# excerpts, XLOG Technologies AG has at least obtained the right to
# reproduce, change and translate the information.
#
# Reproduction is restricted to the whole unaltered document. Reproduction
# of the information is only allowed for non-commercial uses. Selling,
# giving away or letting of the execution of the library is prohibited.
# The library can be distributed as part of your applications and libraries
# for execution provided this comment remains unchanged.
#
# Restrictions
# Only to be distributed with programs that add significant and primary
# functionality to the library. Not to be distributed with additional
# software intended to replace any components of the library.
#
# Trademarks
# Jekejeke is a registered trademark of XLOG Technologies AG.
##

from nova.core import (
    set, make_check, for_later,
    exec_build, exec_unify, int32, get_engine)
from doglet.misc.xbarlib import (
    cpu_xbar_poll, cpu_xbar_offer)
import asyncio
import threading


MAX_TILT = 64
GROUP_SIZE = 8

class CpuMap:
    def __init__(self):
        self.code = None
        self.offset = None
        self.comm = None
        self.state = None


class CpuWarp:
    def __init__(self):
        super().__init__()
        self.map = None
        self.mfrom = 0
        self.to = 0
        self.thread = None


def run(warp):
    pi = warp.map
    i = warp.mfrom
    while i < warp.to:
        pi.state[pi.offset[i] - 3] = i
        i += 1
    active = True
    while active:
        active = False
        i = warp.mfrom
        while i < warp.to:
            if run_id(pi, i):
                active = True
            i += 1


def run_id(pi, mid):
    base = pi.offset[mid]
    pc = pi.state[base-2]
    accu = pi.state[base-1]
    k = 0
    while k < MAX_TILT:
        if pc < len(pi.code):
            instr = pi.code[pc]
            value = hack_get(pi, instr, pc, base)
            pc = hack_set(pi, instr, accu, pc, base)
            accu = hack_fun(instr, accu, value)
        else:
            pi.state[base-2] = pc
            pi.state[base-1] = accu
            return False
        k += 1
    pi.state[base-2] = pc
    pi.state[base-1] = accu
    return True


def hack_get(pi, instr, pc, base):
    match (instr>>28) & 0x0F:
        case 0:  # cst
            cst = (instr & 0x00FFFFFF) - 0x00800000
            return cst
        case 1:  # get
            get = (instr & 0x00FFFFFF) - 0x00800000
            return pi.state[base+get]
        case 2:  # ext
            return pi.code[pc+1]
        case 3:  # out
            out = (instr & 0x00FFFFFF) - 0x00800000
            return extra_output(pi, out, base)
        case 4:  # in
            mmin = (instr & 0x00FFFFFF) - 0x00800000
            return extra_input(pi, mmin, base)
        case 5:  # set
            return 0
        case 6:  # bra
            return pc+1
        case 7:  # brz
            return pc+1
        case 8:  # jma
            return pc+1
        case 9:  # jmz
            return pc+1
        case _:
            raise ValueError("illegal mode")


def hack_set(pi, instr, accu, pc, base):
    match (instr>>28) & 0x0F:
        case 0:  # cst
            return pc+1
        case 1:  # get
            return pc+1
        case 2:  # ext
            return pc+2
        case 3:  # out
            return pc+1
        case 4:  # in
            return pc+1
        case 5:  # set
            mset = (instr & 0x00FFFFFF) - 0x00800000
            pi.state[base+mset] = accu
            return pc+1
        case 6:  # bra
            bra = (instr & 0x00FFFFFF) - 0x00800000
            return bra
        case 7:  # brz
            brz = (instr & 0x00FFFFFF) - 0x00800000
            return brz if accu == 0 else pc + 1
        case 8:  # jma
            jma = (instr & 0x00FFFFFF) - 0x00800000
            return pi.state[base+jma]
        case 9:  # jmz
            jmz = (instr & 0x00FFFFFF) - 0x00800000
            return pi.state[base+jmz] if accu == 0 else pc + 1
        case _:
            raise ValueError("illegal mode")


def hack_fun(instr, accu, value):
    match (instr>>24) & 0x0F:
        case 0: # mov
            return value
        case 1: # neg
            return int32(- value)
        case 2: # add
            return int32(accu + value)
        case 3: # sub
            return int32(accu - value)
        case 4: # mul
            return int32(accu * value)
        case 5: # zdiv
            return int32(accu // value)
        case 6: # rem
            return accu % value
        case 7: # min
            return min(accu, value)
        case 8: # max
            return max(accu, value)
        case 9: # eq
            return 1 if accu == value else 0
        case 10: # nq
            return 1 if accu != value else 0
        case 11: # ls
            return 1 if accu < value else 0
        case 12: # gr
            return 1 if accu > value else 0
        case 13: # lq
            return 1 if accu <= value else 0
        case 14: # gq
            return 1 if accu >= value else 0
        case _:
            raise ValueError("illegal fun")


#################################################################
# Hack Output/Input                                             #
#################################################################

def extra_output(pi, obj, base):
    chan = pi.comm[obj]
    return 1 if cpu_xbar_offer(chan, pi.state, base+1, pi.state[base]) else 0


def extra_input(pi, obj, base):
    chan = pi.comm[obj]
    mlen = pi.state[base]
    res = cpu_xbar_poll(chan, pi.state, base + 1, mlen)
    if res == -1:
        return 0
    if res != mlen:
        pi.state[base] = res
    return 1


#################################################################
# Hack Constructors                                             #
#################################################################

###
# test_cpu_comp_new(C, O, T, S, M): internal only
# The predicate succeeds in M with a new CPU backed π-WAM for
# the code buffer C, the offsets buffer O, the channel table T
# and the state buffer S.
##
def test_cpu_comp_new(args):
    res = CpuMap()
    res.code = exec_build(args[0])
    res.offset = exec_build(args[1])
    res.comm = exec_build(args[2])
    res.state = exec_build(args[3])
    return exec_unify(args[4], res)


###
# test_cpu_comp_count(M, C): internal only
# The predicate succeeds in C with the current
# number of groups in the CPU backed π-WAM M.
##
def test_cpu_comp_count(args):
    alpha = exec_build(args[0])
    res = len(alpha.offset)
    res = (res+GROUP_SIZE-1)//GROUP_SIZE
    return exec_unify(args[1], res)


#################################################################
# Hack Interface                                                #
#################################################################

###
# test_cpu_group_new(G, W): internal only
# The predicate succeeds in G with a
# new group for the CPU backed π-WAM M.
##
def test_cpu_group_new(args):
    alpha = exec_build(args[0])
    res = CpuWarp()
    res.map = alpha
    res.thread = threading.Thread(target=run, args=(res,))
    return exec_unify(args[1], res)


###
# test_cpu_group_start(G, I): internal only
# The predicate succeeds. As a side effect it
# starts the warp G at group index I.
##
def test_cpu_group_start(args):
    alpha = exec_build(args[0])
    beta = exec_build(args[1])
    at = int32(beta)*GROUP_SIZE
    mlen = min(len(alpha.map.offset) - at, GROUP_SIZE)
    alpha.mfrom = at
    alpha.to = at+mlen
    alpha.thread.start()
    return True


###
# test_cpu_group_join(G, P): internal only
# The predicate succeeds in P with a new promise
# that waits for the group G to finish.
##
def test_cpu_group_join(args):
    alpha = exec_build(args[0])
    return exec_unify(args[1], for_later(
        cpu_join_promise(get_engine(), alpha.thread)))


async def cpu_join_promise(en, alpha):
    await asyncio.to_thread(alpha.join)


###
# test_cpu_group_free(G): internal only
# The predicate succeeds. As a side effect
# it frees the group G.
##
def test_cpu_group_free(args):
    return True


#################################################################
# Hack Lib Init                                                 #
#################################################################

def main():
    set("cpu_comp_new", 5, make_check(test_cpu_comp_new))
    set("cpu_comp_count", 2, make_check(test_cpu_comp_count))
    set("cpu_group_new", 2, make_check(test_cpu_group_new))
    set("cpu_group_start", 2, make_check(test_cpu_group_start))
    set("cpu_group_join", 2, make_check(test_cpu_group_join))
    set("cpu_group_free", 1, make_check(test_cpu_group_free))
