# https://zhuanlan.zhihu.com/p/623697843

# mamba create -n golang -c conda-forge go
# conda activate golang
# cd E:\tmp\ISLAND
# Get-Item -Path Env:\CONDA*
# $env:GOROOT = "$env:CONDA_PREFIX\go"
# go version
# go mod init cst
# go get github.com/regomne/eutil/codec
# go get github.com/regomne/eutil/textFile
# # https://github.com/regomne/chinesize/blob/master/CatSystem2/cstTextProc/cst.go
# go build .\cst.go
#
# E:\tmp\ISLAND\cst.exe -e -cst E:\tmp\ISLAND\cst\BAD_01.cst -o E:\tmp\ISLAND\cst\BAD_01.txt -cp 932

import os, sys
import struct
import zlib

warnings = []


def warn(value):
    warnings.append(value)


def clearWarnings():
    global warnings
    warnings = []


def printWarnings(sc):
    global warnings
    for wi in warnings:
        print('[WARNING]', sc, wi)
    clearWarnings()


def cst2bin(datcst):
    tag, sizcst, sizbin = struct.unpack_from('8sII', datcst)
    if tag != b'CatScene':
        raise Exception('Label Mismatch')
    datcst = datcst[16:]
    if sizcst != len(datcst):
        raise Exception('Size Ante Decompress Mismatch')
    datbin = zlib.decompress(datcst)
    if sizbin != len(datbin):
        raise Exception('Size Post Decompress Mismatch')
    return datbin


def bin2cst(datbin):
    datcst = zlib.compress(datbin)
    return b'CatScene' + struct.pack('II', len(datcst), len(datbin)) + datcst


class FormatCST:
    def __init__(self, fc):
        b = cst2bin(fc.read())
        (h0, self.h1, self.h2, self.h3), b = struct.unpack_from('4I', b), b[16:]
        self.b1, b2, b3 = b[:self.h2], b[self.h2:self.h3], b[self.h3:]
        if h0 != len(b) or self.h1 * 8 != self.h2 or (self.h3 - self.h2) % 4 != 0:
            raise Exception('Integrity Constraint 0 Violated')

        it = struct.iter_unpack('II', self.b1)
        flag = True
        self.n1 = 0
        while flag:
            try:
                d10, d11 = next(it)
                if d11 != self.n1:
                    flag = False
                self.n1 += d10
            except StopIteration:
                break
        if not flag or self.n1 * 4 != self.h3 - self.h2:
            raise Exception('Integrity Constraint 1 Violated')

        it = struct.iter_unpack('I', b2)
        d2 = []
        while True:
            try:
                d2.append(*next(it))
            except StopIteration:
                break
        if self.n1 != len(d2):
            raise Exception('Integrity Constraint 2 Violated')

        ofs = 0
        self.d3 = []
        for i in range(self.n1):
            if ofs < d2[i]:
                warn('Unaccessible Fragment Offset 0x{0:08X}'.format(ofs))
                ofs = d2[i]
            if ofs > d2[i]:
                raise Exception('Overflow Offset 0x{0:08X}'.format(ofs))
            try:
                d30, d31, d32 = struct.unpack_from('3B', b3, ofs)
            except Exception:
                raise Exception('Content Truncated')
            if d30 != 0x01:
                raise Exception('Invalid Offset 0x{0:08X}'.format(ofs))
            if d31 not in (0x02, 0x20, 0x21, 0x30):
                warn('Unknown Code 0x01{1:02X} Offset 0x{0:08X}'.format(ofs, d31))
            ofs += 3
            while d32 != 0x00:
                try:
                    d32, = struct.unpack_from('B', b3, ofs)
                except Exception:
                    raise Exception('Content Truncated')
                ofs += 1
            self.d3.append(b3[d2[i]: ofs])
        if ofs < len(b3):
            warn('Unaccessible Fragment Offset 0x{0:08X}'.format(ofs))

    def iter(self):
        self.idx = -1
        self.fslc = False

    def next(self, skp=True):
        self.idx += 1
        if skp:
            while self.idx < self.n1:
                if self.fslc:
                    break
                d31, = struct.unpack_from('B', self.d3[self.idx], 1)
                if d31 in (0x20, 0x21):
                    break
                if d31 == 0x30 and self.d3[self.idx][2:8] == b'scene\x20':
                    break
                if d31 == 0x30 and self.d3[self.idx][2:] == b'fselect\x00':
                    self.fslc = True
                self.idx += 1
        if self.idx >= self.n1:
            raise StopIteration

    def get(self, skp=True):
        if skp:
            return self.d3[self.idx][2:-1]
        else:
            return b'<\\x01><\\x' + bytes('{0:02X}'.format(self.d3[self.idx][1]), encoding='utf-8') + b'>' + self.d3[
                                                                                                                 self.idx][
                                                                                                             2:-1] + b'<\\x00>'

    def rep(self, bn):
        self.d3[self.idx] = self.d3[self.idx][:2] + bn + b'\x00'

    def pac(self):
        b2, b3 = b'', b''
        ofs = 0
        for i in range(self.n1):
            b2 += struct.pack('I', ofs)
            b3 += self.d3[i]
            ofs += len(self.d3[i])
        b0 = struct.pack('4I', self.h3 + ofs, self.h1, self.h2, self.h3)
        return b0 + self.b1 + b2 + b3


pathcst = 'scene_cst'
pathbin = 'scene_bin'
pathtxt = 'scene_txt'
pathdst = 'scene_dst'


def depacst():
    liscst = os.listdir(pathcst)
    if not os.path.exists(pathbin):
        os.makedirs(pathbin)
    s0, s1 = 0, 0
    for sc in liscst:
        if not sc.endswith('.cst'):
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            b = cst2bin(f.read())
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        sb = sc[:-3] + 'bin'
        f = open(os.path.join(pathbin, sb), 'wb')
        f.write(b)
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


def unpacst(skp=True):
    liscst = os.listdir(pathcst)
    if not os.path.exists(pathtxt):
        os.makedirs(pathtxt)
    s0, s1 = 0, 0
    for sc in liscst:
        if not sc.endswith('.cst'):
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            c = FormatCST(f)
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        st = sc[:-3] + 'txt'
        f = open(os.path.join(pathtxt, st), 'wb')
        c.iter()
        while True:
            try:
                c.next(skp)
                f.write(c.get(skp))
                f.write(b'\x0D\x0A')
            except StopIteration:
                break
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


def repacst():
    liscst = os.listdir(pathcst)
    listxt = os.listdir(pathtxt)
    if not os.path.exists(pathdst):
        os.makedirs(pathdst)
    s0, s1 = 0, 0
    for st in listxt:
        if not st.endswith('.txt'):
            continue
        sc = st[:-3] + 'cst'
        if sc not in liscst:
            print('[WARNING] Original CST File Missing: ' + sc)
            continue
        s1 += 1
        clearWarnings()

        f = open(os.path.join(pathcst, sc), 'rb')
        try:
            c = FormatCST(f)
        except Exception as e:
            print('[ERROR]', sc, e)
            continue
        finally:
            f.close()

        st = sc[:-3] + 'txt'
        f = open(os.path.join(pathtxt, st), 'rb')
        c.iter()
        flag = True
        s = 0
        while True:
            try:
                c.next()
                bn = b''
                while True:
                    bi = f.read(1)
                    di, = struct.unpack('B', bi)
                    if di < 0x20:
                        break
                    bn += bi
                if di != 0x0D:
                    flag = False
                    break
                bi = f.read(1)
                di, = struct.unpack('B', bi)
                if di != 0x0A:
                    flag = False
                    break
                c.rep(bn)
                s += 1
            except StopIteration:
                break
            except Exception:
                warn('Lack of Text')
                break
        f.close()
        if not flag:
            print('[ERROR]', st, 'Invalid Byte 0x{0:02X}'.format(di))
            continue
        f = open(os.path.join(pathdst, sc), 'wb')
        f.write(bin2cst(c.pac()))
        f.close()

        s0 += 1
        printWarnings(sc)
    return (s0, s1)


if __name__ == '__main__':
    pathcst = r'E:\tmp\ISLAND\cst'
    liscst = os.listdir(pathcst)
    tag = 0
    if tag not in (0, 1, 2, 3):
        print('Invalid Parametre')
        sys.exit()
    if tag == 0:
        s0, s1 = unpacst()
    if tag == 1:
        s0, s1 = repacst()
    if tag == 2:
        s0, s1 = depacst()
    if tag == 3:
        s0, s1 = unpacst(False)
    print('%d / %d completed' % (s0, s1))