import unittest
from contextlib import redirect_stdout
from io import StringIO

from tools.check_setup import check_main_routes, check_readme_security


class CheckSetupValidationTest(unittest.TestCase):
    def test_main_route_scan_accepts_required_routes_and_local_cors(self) -> None:
        source = """
app.add_middleware(CORSMiddleware, allow_origins=["http://127.0.0.1:8000"])
@app.get("/api/health")
async def health(): pass
@app.post("/api/verify")
async def verify(): pass
@app.post("/api/sign")
async def sign(): pass
@app.post("/api/read-certificate")
async def read_certificate(): pass
"""

        with redirect_stdout(StringIO()):
            errors = check_main_routes(source)

        self.assertEqual(errors, [])

    def test_main_route_scan_reports_missing_read_certificate(self) -> None:
        source = """
allow_origins=["http://127.0.0.1:8000"]
@app.get("/api/health")
@app.post("/api/verify")
@app.post("/api/sign")
"""

        with redirect_stdout(StringIO()):
            errors = check_main_routes(source)

        self.assertIn("missing FastAPI route: read_certificate", errors)

    def test_readme_security_scan_requires_local_only_warning(self) -> None:
        readme = """
--host 127.0.0.1
VPS / クラウド / 共有サーバー等にデプロイしては絶対にいけません
.jpkiimg
/api/read-certificate
"""

        with redirect_stdout(StringIO()):
            errors = check_readme_security(readme)

        self.assertEqual(errors, [])


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