#!/usr/bin/env python3
import os
import unittest
import llvmlite.ir as ir

from src.llvm_py.llvm_builder import NyashLLVMBuilder


class TestStrlenFast(unittest.TestCase):
    def setUp(self):
        # Ensure FAST toggle is ON for this test
        os.environ['NYASH_LLVM_FAST'] = '1'

    def tearDown(self):
        os.environ.pop('NYASH_LLVM_FAST', None)

    def test_newbox_string_length_fast_lowering(self):
        # Minimal MIR JSON v0-like: const "hello" → newbox StringBox(arg) → boxcall length
        mir = {
            "functions": [
                {
                    "name": "main",
                    "params": [],
                    "blocks": [
                        {
                            "id": 1,
                            "instructions": [
                                {"op": "const", "dst": 10, "value": {"type": "string", "value": "hello"}},
                                {"op": "newbox", "dst": 20, "box_type": "StringBox", "args": [10]},
                                {"op": "boxcall", "dst": 30, "box_val": 20, "method": "length", "args": []},
                                {"op": "ret", "value": 30},
                            ]
                        }
                    ]
                }
            ]
        }

        b = NyashLLVMBuilder()
        ir_txt = b.build_from_mir(mir)
        # Must reference the neutral kernel symbol for FAST strlen
        self.assertIn('declare i64 @nyrt_string_length(i8*, i64)', ir_txt or '')
        # And a call site should be present
        self.assertIn('call i64 @nyrt_string_length', ir_txt)


if __name__ == '__main__':
    unittest.main()

