"""Tests for the pm2 config (ecosystem.config.cjs):  python3 -m unittest scripts/test_ecosystem.py"""
import json
import os
import pathlib
import shutil
import subprocess
import unittest

ROOT = pathlib.Path(__file__).resolve().parent.parent
LOAD = "console.log(JSON.stringify(require(process.argv[1]).apps))"


@unittest.skipUnless(shutil.which('node'), 'needs node')
class Ecosystem(unittest.TestCase):
    def apps(self, **env):
        out = subprocess.run(['node', '-e', LOAD, str(ROOT / 'ecosystem.config.cjs')], capture_output=True, text=True,
                             env={**os.environ, **env}, check=True).stdout
        return json.loads(out)

    def test_runs_serve_py_with_the_mcp_bridge_from_the_repo(self):
        [app] = self.apps()
        self.assertEqual(app['name'], 'webtt')
        self.assertEqual(pathlib.Path(app['cwd']), ROOT)
        self.assertEqual(app['script'], 'scripts/serve.py')
        self.assertEqual(app['args'], '8289 --mcp mcp.config.json --compute')
        self.assertEqual(app['env']['PYTHONUNBUFFERED'], '1')

    def test_python_is_an_absolute_path_so_boot_time_path_does_not_matter(self):
        [app] = self.apps()
        self.assertTrue(os.path.isabs(app['interpreter']), app['interpreter'])
        self.assertTrue(os.access(app['interpreter'], os.X_OK))

    def test_python_and_port_can_be_overridden(self):
        [app] = self.apps(WEBTT_PYTHON='/opt/py/bin/python3', WEBTT_PORT='9000')
        self.assertEqual(app['interpreter'], '/opt/py/bin/python3')
        self.assertTrue(app['args'].startswith('9000 '))

    def test_restarts_are_bounded_and_shutdown_waits_for_mcp_children(self):
        [app] = self.apps()
        self.assertTrue(app['autorestart'])
        self.assertGreater(app['max_restarts'], 0)
        self.assertGreaterEqual(app['kill_timeout'], 5000)


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