"""Replay the delivered AWL and HMI script with no third-party dependencies.

This small interpreter implements the instructions in the delivered sources.
It is independent of Micro/WIN, ForceControl and physical communications.
"""
from collections import defaultdict
from itertools import product
import csv
from pathlib import Path
import operator
import re
import sys

ROOT = Path(__file__).resolve().parents[1]
P = ROOT / '01_PLC'
HMI = ROOT / '02_ForceControl'
COMPARE = {'=':operator.eq, '<>':operator.ne, '<':operator.lt, '>':operator.gt,
           '<=':operator.le, '>=':operator.ge}
OUT = ('FAN_OUT', 'MIST_OUT', 'HEAT_OUT', 'ALARM_CODE', 'FAN_REASON', 'ALARM_OUT', 'CTRL_OK')
with (P/'PLC联机点位对照.csv').open(encoding='utf-8-sig',newline='') as f:
    plc_points = list(csv.DictReader(f))
SIGNALS = {point['点名']:point['PLC字地址'] for point in plc_points}
assert len(plc_points) == len(SIGNALS) == 19
assert len({int(a[2:])+i for a in SIGNALS.values() for i in (0,1)}) == 2*len(SIGNALS)
assert 'VW134' not in SIGNALS.values()

with (HMI/'点位配置对照.csv').open(encoding='utf-8-sig',newline='') as f:
    local_points = list(csv.DictReader(f))
local_names = [point['点名'] for point in local_points]
sim_names = set(local_names)
assert len(local_names) == len(sim_names) == 17
assert sim_names == set(SIGNALS) - {'HEARTBEAT', 'LINK_OK'}
assert local_names[local_names.index('SENSOR_OK')+1] == 'FAN_OUT'
sim_sources = ['SIM_01_OnStart.txt', 'SIM_02_Every500ms.txt', '按钮脚本_逐段复制.txt']
references = set()
for name in sim_sources:
    code = (HMI/name).read_text(encoding='utf-8-sig')
    references.update(re.findall(r'\b([A-Z][A-Z0-9_]+)\.PV\b',code))
assert references == sim_names

class Plc:
    def __init__(self):
        awl = (P/'MushroomRoom_S7_200.awl').read_text()
        body = awl.split('BEGIN\n',1)[1].split('END_ORGANIZATION_BLOCK',1)[0].strip()
        assert body == (P/'MushroomRoom_OB1_STL.txt').read_text().strip()
        self.code = []
        for line in body.splitlines():
            line = line.split('//',1)[0].strip()
            if line and not line.startswith('NETWORK '):
                op, args = line.split(None,1)
                self.code.append((op,*[arg.strip() for arg in args.split(',')]))
        self.mem = defaultdict(int, {'SM0.0':1,'SM0.1':1})
        self.timer = 0
        self.scan()

    def val(self, arg):
        return int(arg) if arg.lstrip('-').isdigit() else self.mem[arg]

    def scan(self, changes=None, beat=False, dt=0):
        for key,value in (changes or {}).items():
            self.mem[SIGNALS[key]]=value
        if beat:
            self.mem['VW132'] ^= 1
        rlo = False
        for op,*args in self.code:
            if op == 'LD':
                rlo = bool(self.val(args[0]))
            elif op == 'LDN':
                rlo = not self.val(args[0])
            elif op == 'A':
                rlo = rlo and bool(self.val(args[0]))
            elif op == 'AN':
                rlo = rlo and not self.val(args[0])
            elif op == 'O':
                rlo = rlo or bool(self.val(args[0]))
            elif op == '=':
                self.mem[args[0]] = int(rlo)
            elif op == 'MOVW':
                if rlo:
                    self.mem[args[1]] = self.val(args[0])
            elif op == 'MOVB':
                if rlo:
                    assert args[0]=='0' and args[1] in {'MB0','MB1'}
                    for b in range(8):
                        self.mem[f'M{args[1][-1]}.{b}'] = 0
            elif op == 'TON':
                assert args[0]=='T37'
                self.timer = self.timer+dt if rlo else 0
                self.mem[args[0]] = int(self.timer>=self.val(args[1])*100)
            else:
                prefix,rel=op.split('W',1)
                predicate=COMPARE[rel](self.val(args[0]),self.val(args[1]))
                if prefix=='LD':
                    rlo=predicate
                elif prefix=='A':
                    rlo=rlo and predicate
                elif prefix=='O':
                    rlo=rlo or predicate
                else:
                    raise ValueError(op)
        self.mem['SM0.1']=0
        result = tuple(self.mem[SIGNALS[k]] for k in OUT)
        assert (*result[:3],result[5]) == tuple(self.mem[f'Q0.{i}'] for i in range(4))
        return result

def compile_script(code):
    # Build a Python program from the local script's restricted syntax.
    # Validate identifiers and operators before translating, and allow no builtins.
    lines=[]
    depth=0
    for line in code.splitlines():
        line=line.split('//',1)[0].strip()
        if not line:
            continue
        if line=='ENDIF':
            depth-=1
            assert depth>=0
            continue
        if line=='ELSE':
            assert depth>0
            lines.append('    '*(depth-1)+'else:')
            continue
        assert re.fullmatch(r'[a-zA-Z0-9_. <>|&=();+-]+',line), line
        assert '!=' not in line
        line=re.sub(r'\b([A-Z][A-Z0-9_]+)\.PV\b',
                    lambda m: m[1] if m[1] in SIGNALS else sys.exit('Unknown point '+m[1]),line)
        assert '.' not in line
        line=line.replace('&&',' and ').replace('||',' or ').replace('<>','!=')
        if line.startswith('IF ') and line.endswith(' THEN'):
            lines.append('    '*depth+'if '+line[3:-5]+':')
            depth+=1
        else:
            assert line.endswith(';') and re.fullmatch(r'\w+ = .+;',line),line
            lines.append('    '*depth+line[:-1])
    assert depth==0
    return compile('\n'.join(lines),'<ForceControl script>','exec')

def script(path):
    return compile_script(path.read_text(encoding='utf-8-sig'))

class Sim:
    start=script(HMI/'SIM_01_OnStart.txt')
    periodic=script(HMI/'SIM_02_Every500ms.txt')
    hb=script(P/'PLC_Every1000ms_Heartbeat.txt')
    def __init__(self):
        self.mem = {}
        self.run(self.start)
    def run(self, code):
        exec(code,{'__builtins__':{}},self.mem)
    def scan(self, changes=None):
        self.mem.update(changes or {})
        self.run(self.periodic)
        return tuple(self.mem[k] for k in OUT)

# Results contain fan, mist, heat, alarm, fan reason, alarm relay, control permission.
def result(f=0,m=0,h=0,a=0,r=0,c=1):
    return f,m,h,a,r,int(a!=0),c

CASES=[
 ('01','启动后正常',{'RUN_CMD':1},result()),
 ('02','低湿 85.0 边界启动',{'HUM10':850},result(m=1)),
 ('03','湿度回升 89.9 保持',{'HUM10':899},result(m=1)),
 ('04','湿度 90.0 停止',{'HUM10':900},result()),
 ('05','湿度回落 85.1 不启动',{'HUM10':851},result()),
 ('06','CO₂ 达 1000 强排并抑制加湿',{'HUM10':820,'CO2_PPM':1000},result(f=1,r=1)),
 ('07','CO₂ 851 仍保持排风',{'CO2_PPM':851},result(f=1,r=1)),
 ('08','CO₂ 850 关风且恢复加湿',{'CO2_PPM':850},result(m=1)),
 ('09','CO₂ 1300 与缺水并发',{'CO2_PPM':1300,'WATER_OK':0},result(f=1,r=1,a=2)),
 ('10','CO₂ 1199 不报警但继续排风，显示缺水',{'CO2_PPM':1199},result(f=1,r=1,a=3)),
 ('11','缺水时湿度低但不加湿',{'CO2_PPM':700},result(a=3)),
 ('12','补水后恢复加湿',{'WATER_OK':1},result(m=1)),
 ('13','低温 18.0 启动加热',{'TEMP10':180,'HUM10':900},result(h=1)),
 ('14','低温回升至 19.9 保持',{'TEMP10':199},result(h=1)),
 ('15','温度 20.0 停止加热',{'TEMP10':200},result()),
 ('16','温度 24.0 开高温排风',{'TEMP10':240},result(f=1,r=2)),
 ('17','温度 22.1 保持排风',{'TEMP10':221},result(f=1,r=2)),
 ('18','温度 22.0 停风',{'TEMP10':220},result()),
 ('19','CO₂ 与高温同到，显示 CO₂ 原因',{'TEMP10':270,'CO2_PPM':1300},result(f=1,r=1,a=2)),
 ('20','CO₂ 降至退出阈值仍因高温排风',{'CO2_PPM':850},result(f=1,r=2,a=4)),
 ('21','高湿达到 96.0 边界',{'TEMP10':210,'HUM10':960},result(a=5)),
 ('22','湿度降到 95.9 清除报警',{'HUM10':959},result()),
 ('23','手动加热',{'AUTO_CMD':0,'MAN_HEAT':1},result(h=1)),
 ('24','手动风机禁止加热',{'MAN_FAN':1},result(f=1,r=3)),
 ('25','手动缺水阻止加湿',{'MAN_MIST':1,'WATER_OK':0},result(f=1,r=3,a=3)),
 ('26','手动高 CO₂ 优先于手动风机原因',{'CO2_PPM':1300},result(f=1,r=1,a=2)),
 ('27','关闭手动风机请求仍保留 CO₂ 排风',{'MAN_FAN':0},result(f=1,r=1,a=2)),
 ('28','手动模式测量故障时执行器全停',{'SENSOR_OK':0},result(a=1,c=0)),
 ('29','湿度超过 100.0，继续测量故障',{'SENSOR_OK':1,'HUM10':1001},result(a=1,c=0)),
 ('30','恢复有效后仍按缺水联锁',{'HUM10':880,'CO2_PPM':700},result(h=1,a=3)),
 ('31','全局停止清输出及报警',{'RUN_CMD':0},result(c=0)),
 ('32','重新启动且手动请求已清，可进入自动',{'RUN_CMD':1,'AUTO_CMD':1,'MAN_FAN':0,'MAN_MIST':0,'MAN_HEAT':0,'WATER_OK':1},result()),
 ('33','负温度符合测量范围并触发低温报警',{'TEMP10':-100},result(h=1,a=4)),
 ('34','负温度越出合理范围',{'TEMP10':-101},result(a=1,c=0)),
 ('35','低湿报警边界 75.0',{'TEMP10':210,'HUM10':750},result(m=1,a=5)),
]

def encode(v):
    return '/'.join(map(str,v))

def main():
    plc,sim=Plc(),Sim()
    assert {key:sim.mem[key] for key in sim_names} == {
        point['点名']:int(point['初始值']) for point in local_points
    }
    records=[]
    assert plc.scan() == sim.scan() == result(c=0)
    assert plc.scan(beat=True)==result(c=0)
    for ident,desc,changes,expected in CASES:
        l=plc.scan(changes,beat=True)
        s=sim.scan(changes)
        assert expected==l==s,(ident,expected,l,s)
        records.append((ident,desc, ' | '.join(f'{k}={v}' for k,v in changes.items()),encode(expected),encode(l),encode(s),'通过'))
    # Re-arm sequencing after losing heartbeat.
    plc = Plc()
    assert plc.scan({'RUN_CMD':1,'TEMP10':270})==result(a=6,c=0)
    assert plc.scan(beat=True)==result(a=6,c=0)
    assert plc.scan({'RUN_CMD':0})==result(c=0)
    assert plc.scan({'RUN_CMD':1})==result(f=1,r=2,a=4)
    steps=[
      ('36','最后一次心跳后 4.9 秒',{},False,4900,result(f=1,r=2,a=4)),
      ('37','心跳满 5 秒超时',{},False,100,result(a=6,c=0)),
      ('38','恢复心跳，运行请求仍为 1 时禁止自启',{},True,0,result(a=6,c=0)),
      ('39','有心跳时先停机',{'RUN_CMD':0},False,0,result(c=0)),
      ('40','再次启动恢复高温排风',{'RUN_CMD':1},False,0,result(f=1,r=2,a=4)),
    ]
    for ident,desc,changes,beat,dt,expected in steps:
        actual=plc.scan(changes,beat=beat,dt=dt)
        assert actual==expected
        records.append((ident,desc,'仅 PLC 控制分支',encode(expected),encode(actual),'—','通过'))
    # Replay the actual button source and online heartbeat script.
    buttons=(HMI/'按钮脚本_逐段复制.txt').read_text(encoding='utf-8-sig')
    scripts={label:compile_script(code) for label,code in re.findall(r'^// \[(.*?)\][^\n]*\n(.*?)(?=^// \[|\Z)',buttons,re.M|re.S)}
    assert len(scripts)==14
    sim = Sim()
    def push(label):
        sim.run(scripts[label])
        return sim.scan()
    assert push('启动') == result()
    assert push('低湿') == result(m=1)
    assert push('CO2高且低湿') == result(f=1,r=1,a=2)
    assert push('缺水') == result(a=3)
    assert push('低温') == result(h=1)
    assert push('高温') == result(f=1,r=2,a=4)
    assert push('测量故障') == result(a=1,c=0)
    assert push('正常复位') == result()
    assert push('手动') == result()
    assert push('手动风机') == result(f=1,r=3)
    assert push('手动加热') == result(f=1,r=3)
    assert push('手动风机') == result(h=1)
    assert push('手动加湿') == result(m=1,h=1)
    assert push('停止') == result(c=0)
    assert all(sim.mem[k]==0 for k in ('MAN_FAN','MAN_MIST','MAN_HEAT'))
    assert push('自动') == result(c=0)
    sim.mem['hb_tick']=0
    for v in (1,0,1,0):
        sim.run(sim.hb)
        assert sim.mem['HEARTBEAT']==v
    # Compare both sources over a grid including both sides of all switching thresholds.
    plc,sim=Plc(),Sim()
    plc.scan(beat=True)
    grid = product((159,180,199,200,220,221,239,240,260),
                   (749,850,851,899,900,960,1001),
                   (700,850,851,999,1000,1199,1200), (0,1),(0,1))
    count=0
    for t,h,c,m,w in grid:
        data=dict(RUN_CMD=1,TEMP10=t,HUM10=h,CO2_PPM=c,AUTO_CMD=m,WATER_OK=w,
                  MAN_FAN=0,MAN_MIST=1,MAN_HEAT=1,SENSOR_OK=1)
        assert plc.scan(data,beat=True)==sim.scan(data),data
        count+=1
    if len(sys.argv)>1 and sys.argv[1]=='--export':
        with (Path(__file__).parent/'源代码逻辑回放结果.csv').open('w',newline='',encoding='utf-8-sig') as f:
            output=csv.writer(f)
            output.writerow(('编号','用例','变化值','预期','AWL回放','SIM脚本回放','源代码回放状态'))
            output.writerows(records)
    print(f'{len(records)} scripted cases passed; {count} cross-source input combinations matched; button and heartbeat scripts passed.')
    print('Point tables passed: 17 unique simulation points and 19 unique PLC points.')
    print('Output tuple: fan/mist/heat/alarm code/fan reason/alarm relay/control enable.')
    print('Source-level replay only. Native compilation, HMI runtime and field I/O are not exercised.')

if __name__=='__main__':
    main()
