import io
import unittest

try:
    from app.main import STATE, app
except ModuleNotFoundError as exc:  # pragma: no cover
    STATE = {}
    app = None
    _IMPORT_ERR = exc
else:
    _IMPORT_ERR = None


def _sample_csv_bytes() -> bytes:
    header = ",".join(
        [
            "id",
            "name",
            "depth",
            "mimeType",
            "modifiedTime",
            "size",
            "owners.0.emailAddress",
            "owners.0.displayName",
            "path.0",
            "sharingUser.emailAddress",
            "lastModifyingUser.emailAddress",
            "permission.type",
            "permission.role",
            "permission.emailAddress",
            "permission.domain",
            "permission.allowFileDiscovery",
            "permission.id",
            "permission.deleted",
        ]
    )
    row = ",".join(
        [
            "file-1",
            "doc.txt",
            "2",
            "text/plain",
            "2026-02-19T10:00:00Z",
            "128",
            "owner@example.com",
            "Owner",
            "My Drive/docs/doc.txt",
            "owner@example.com",
            "owner@example.com",
            "user",
            "owner",
            "owner@example.com",
            "",
            "false",
            "perm-1",
            "false",
        ]
    )
    return f"{header}\n{row}\n".encode("utf-8")


class UploadFlowE2ETest(unittest.TestCase):
    @unittest.skipIf(app is None, f"Flask runtime unavailable: {_IMPORT_ERR}")
    def test_upload_renders_versioned_explorer_and_operational_panel(self) -> None:
        client = app.test_client()
        res = client.post(
            "/upload",
            data={"csv_file": (io.BytesIO(_sample_csv_bytes()), "sample.csv")},
            content_type="multipart/form-data",
            follow_redirects=False,
        )
        self.assertEqual(res.status_code, 302)
        self.assertEqual(res.headers.get("Location"), "/")

        index_html = client.get("/").get_data(as_text=True)
        self.assertIn("Build ID:", index_html)
        self.assertIn("Operational:", index_html)
        self.assertIn("Processing time:", index_html)
        self.assertIn("explorer.html?v=", index_html)

        job = STATE.get("last_job") or {}
        self.assertTrue(job.get("job_id"))
        self.assertTrue(job.get("build_id"))

        explorer = client.get(f"/data/{job['job_id']}/explorer.html").get_data(as_text=True)
        self.assertIn("id=\"splitter1\"", explorer)
        self.assertIn("id=\"splitter2\"", explorer)
        self.assertIn("copy-row-path", explorer)
        self.assertIn("Copy Visible Paths", explorer)
        self.assertIn("const MATRIX_BATCH", explorer)
        self.assertIn("Global Security Score", explorer)
        self.assertIn("data-risk=\"external\"", explorer)
        self.assertIn("let selectedItemId = \"\";", explorer)
        self.assertIn("function masterFocusRows()", explorer)


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