#!/usr/bin/env python3
"""State/approval model, not firmware attestation or a real PLC interface."""
from dataclasses import dataclass, replace
from hashlib import sha256


@dataclass(frozen=True)
class State:
    mode: str
    file_hash: str
    running_logic: str
    retained_limit: int
    calibration_offset: float
    bypass: bool


def trusted(s, approved):
    return (s.mode == 'production' and s.running_logic == approved.running_logic
            and s.file_hash == approved.file_hash
            and s.retained_limit == approved.retained_limit
            and s.calibration_offset == approved.calibration_offset and not s.bypass)


def main():
    approved = State('production', sha256(b'approved project v1').hexdigest(), 'logic-v1', 600, 0.0, False)
    changed = replace(approved, mode='maintenance', retained_limit=900, bypass=True)
    naive_return = replace(changed, mode='production', bypass=False)
    print('approved: file_match=True trusted=True')
    print(f'maintenance: file_match={changed.file_hash == approved.file_hash} trusted={trusted(changed, approved)}')
    print(f'naive return: file_match={naive_return.file_hash == approved.file_hash} trusted={trusted(naive_return, approved)}')
    restored = replace(naive_return, retained_limit=approved.retained_limit)
    print(f'verified restoration: file_match={restored.file_hash == approved.file_hash} trusted={trusted(restored, approved)}')
    assert trusted(approved, approved) and not trusted(changed, approved)
    assert not trusted(naive_return, approved) and trusted(restored, approved)
    for field, value in [('running_logic', 'logic-v2'), ('calibration_offset', 0.2), ('bypass', True)]:
        assert not trusted(replace(approved, **{field: value}), approved)
    print('independent state checks: passed (3/3)')


if __name__ == '__main__':
    main()
