#!/usr/bin/env python3
from __future__ import annotations

import os
import sys
import unittest
from pathlib import Path


HERE = Path(__file__).resolve().parent

os.environ["ANTHROPIC_API_KEY"] = "test-key"

if str(HERE) not in sys.path:
    sys.path.insert(0, str(HERE))

import server as mcp_server  # noqa: E402


MINIMAL_PLAN = {
    "meta": {
        "title": "Shell Integrity Test",
        "description": "Ensure delivery shells do not delete the artifact body.",
        "document_format": "Narrative Scroll",
    },
    "theme": "obsidian-cyan",
    "wrapper": {"engine": "01"},
    "sections": [],
}

BASE_HTML = """<!DOCTYPE html>
<html>
  <head>
    <title>Shell Integrity Test</title>
  </head>
  <body>
    <div id="app">
      <main>
        <h1>Keep me alive</h1>
        <p>This body content should survive repeated shell passes.</p>
      </main>
    </div>
  </body>
</html>
"""

SCRIPT_HEAVY_HTML = """<!DOCTYPE html>
<html>
  <head>
    <title>Script Heavy Artifact</title>
  </head>
  <body>
    <script>
      window.__SCRIPT_HEAVY_APP__ = { ready: true, screens: ['home', 'details'] };
    </script>
  </body>
</html>
"""


class DeliveryShellIntegrityTests(unittest.TestCase):
    def test_reapplying_delivery_shells_preserves_body(self) -> None:
        once = mcp_server.apply_library_shell(BASE_HTML, "artifact-123", "Shell Integrity Test")
        once = mcp_server.apply_next_move_shell(
            once,
            artifact_id="artifact-123",
            artifact_title="Shell Integrity Test",
            prompt="Build a shell integrity test artifact.",
            template_hint=None,
            generation_mode="planned_render",
            plan=MINIMAL_PLAN,
        )

        twice = mcp_server.apply_library_shell(once, "artifact-123", "Shell Integrity Test")
        twice = mcp_server.apply_next_move_shell(
            twice,
            artifact_id="artifact-123",
            artifact_title="Shell Integrity Test",
            prompt="Build a shell integrity test artifact.",
            template_hint=None,
            generation_mode="planned_render",
            plan=MINIMAL_PLAN,
        )

        self.assertIn("Keep me alive", twice)
        self.assertEqual(twice.count("IFX_LIBRARY_SHELL_START"), 1)
        self.assertEqual(twice.count("IFX_NEXT_MOVE_SHELL_START"), 1)
        self.assertTrue(mcp_server.extract_body_residue_without_delivery_shells(twice))

    def test_preservation_guard_raises_when_body_disappears(self) -> None:
        candidate = """<!DOCTYPE html><html><head><title>Broken</title></head><body>
<!-- IFX_LIBRARY_SHELL_START --><div id="ifx-library-save-ui"></div><!-- IFX_LIBRARY_SHELL_END -->
<!-- IFX_NEXT_MOVE_SHELL_START --><div id="ifx-next-move-ui"></div><!-- IFX_NEXT_MOVE_SHELL_END -->
</body></html>"""

        with self.assertRaises(ValueError):
            mcp_server.assert_delivery_shell_preserves_body(
                BASE_HTML,
                candidate,
                artifact_id="artifact-123",
            )

    def test_script_heavy_artifact_body_is_not_treated_as_empty(self) -> None:
        once = mcp_server.apply_library_shell(SCRIPT_HEAVY_HTML, "artifact-456", "Script Heavy Artifact")
        once = mcp_server.apply_next_move_shell(
            once,
            artifact_id="artifact-456",
            artifact_title="Script Heavy Artifact",
            prompt="Build a script-heavy artifact.",
            template_hint=None,
            generation_mode="admin_passthrough_html",
            plan=MINIMAL_PLAN,
        )

        residue = mcp_server.extract_body_residue_without_delivery_shells(once)
        self.assertIn("__SCRIPT_HEAVY_APP__", residue)
        mcp_server.assert_delivery_shell_preserves_body(
            SCRIPT_HEAVY_HTML,
            once,
            artifact_id="artifact-456",
        )

    def test_admin_passthrough_skips_delivery_shell_rewrite(self) -> None:
        result = mcp_server.apply_artifact_delivery_shells(
            BASE_HTML,
            artifact_id="artifact-789",
            artifact_title="Admin Passthrough",
            interaction_mode=None,
            generation_mode="admin_passthrough_html",
            prompt="Host the uploaded HTML exactly as provided.",
            template_hint=None,
            plan=MINIMAL_PLAN,
        )

        self.assertEqual(result, BASE_HTML)
        self.assertNotIn("IFX_LIBRARY_SHELL_START", result)
        self.assertNotIn("IFX_NEXT_MOVE_SHELL_START", result)


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