import importlib.util
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch

SPEC = importlib.util.spec_from_file_location('port_patch', Path(__file__).with_name('install.py'))
mod = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(mod)


class InstallTest(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name).resolve()

    def config(self, instance):
        return ('''upstream foodsafe_release_I { server 127.0.0.1:3300; }
server { listen 4201; underscores_in_headers on;
location ^~ /api/ { proxy_set_header Host $host; proxy_pass http://foodsafe_release_I/; }
location /sample/ { proxy_set_header Host $host; proxy_pass http://foodsafe_release_I; }
location /integration/ { proxy_set_header Host $host; proxy_pass http://frontdesk/; }
}'''.replace('_I', '_' + str(instance))).encode()

    def entry(self, name='target'):
        p = self.root / name
        p.write_bytes(b'old')
        return dict(path=str(p), old=b'old', new=b'new', mode=0o640, uid=p.stat().st_uid, gid=p.stat().st_gid)

    def test_config_both_instances_preserve_integration_headers_and_device_header_option(self):
        for instance in (1, 2):
            result = mod.patch_nginx(self.config(instance), instance)
            self.assertEqual(result.count(b'Host $http_host;'), 2)
            self.assertIn(b'location /integration/ { proxy_set_header Host $host;', result)
            self.assertIn(b'underscores_in_headers on;', result)
            self.assertEqual(mod.patch_nginx(result, instance), result)

    def test_mismatched_instance_and_custom_host_stop(self):
        with self.assertRaises(RuntimeError):
            mod.patch_nginx(self.config(2), 1)
        with self.assertRaises(RuntimeError):
            mod.patch_nginx(self.config(1).replace(b'Host $host;', b'Host custom;', 1), 1)

    def test_plan_validates_both_before_any_write_and_rejects_unknown_code(self):
        roots, configs = [], []
        payload = b'new'
        for instance in (1, 2):
            app = self.root / ('app' + str(instance))
            code = app / mod.REL
            code.parent.mkdir(parents=True)
            code.write_bytes(b'old')
            (app / 'deploy').mkdir()
            (app / 'deploy/nginx.conf').write_bytes(self.config(instance))
            conf = self.root / ('instance' + str(instance) + '.conf')
            conf.write_bytes(self.config(instance))
            roots.append(app)
            configs.append(conf)
        (self.root / 'payload.json').write_text(json.dumps({'sha256': mod.sha(payload)}))
        with patch.object(mod, 'HERE', self.root), patch.object(mod, 'OLD_SHA', mod.sha(b'old')):
            entries = mod.plan(roots, configs, payload)
            self.assertEqual(len(entries), 6)
            self.assertEqual((roots[0] / mod.REL).read_bytes(), b'old')
            (roots[1] / mod.REL).write_bytes(b'unknown')
            with self.assertRaises(RuntimeError):
                mod.plan(roots, configs, payload)
            self.assertEqual((roots[0] / mod.REL).read_bytes(), b'old')

    def test_success_backups_and_modes(self):
        entry = self.entry()
        with patch.object(mod, 'run'), patch.object(mod, 'activate') as active:
            manifest = mod.install([entry], self.root / 'backups')
            active.assert_called_once()
        self.assertEqual(Path(entry['path']).read_bytes(), b'new')
        self.assertEqual(Path(entry['path']).stat().st_mode & 0o777, 0o640)
        data = json.loads(manifest.read_text())
        self.assertEqual((manifest.parent / data[0]['backup']).read_bytes(), b'old')

    def test_activation_failure_restores_all_files_and_services(self):
        entries = [self.entry('one'), self.entry('two')]
        with patch.object(mod, 'run'), patch.object(mod, 'activate', side_effect=[RuntimeError('failed'), None]) as active:
            with self.assertRaisesRegex(RuntimeError, '原文件及服务已恢复'):
                mod.install(entries, self.root / 'backups')
        self.assertEqual(active.call_count, 2)
        for entry in entries:
            self.assertEqual(Path(entry['path']).read_bytes(), b'old')

    def test_precheck_failure_does_not_modify_or_backup(self):
        entry = self.entry()
        with patch.object(mod, 'run', side_effect=RuntimeError('invalid nginx')):
            with self.assertRaises(RuntimeError):
                mod.install([entry], self.root / 'backups')
        self.assertEqual(Path(entry['path']).read_bytes(), b'old')
        self.assertFalse((self.root / 'backups').exists())

    def test_concurrent_change_and_symlink_rejected(self):
        entry = self.entry()
        Path(entry['path']).write_bytes(b'colleague')
        with patch.object(mod, 'run'), patch.object(mod, 'activate') as active:
            with self.assertRaises(RuntimeError):
                mod.install([entry], self.root / 'backups')
            active.assert_not_called()
        self.assertEqual(Path(entry['path']).read_bytes(), b'colleague')
        link = self.root / 'symlink'
        link.symlink_to(entry['path'])
        with self.assertRaises(RuntimeError):
            mod.regular(link)

    def test_rollback_refuses_arbitrary_path(self):
        entry = self.entry()
        manifest = self.root / 'manifest.json'
        manifest.write_text(json.dumps([{'path': entry['path'], 'backup': '0.original'}]))
        with self.assertRaisesRegex(RuntimeError, '路径不在本补丁范围'):
            mod.rollback(manifest)


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