from __future__ import annotations

import argparse
import io
import json
import os
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest.mock import patch

from agent_integration import __main__ as cli
from agent_integration.sessions import SQLiteSessionStore


class AgentCLITests(unittest.TestCase):
    def test_metadata_requires_json_object(self):
        with self.assertRaises(argparse.ArgumentTypeError):
            cli.parse_metadata('["not", "an", "object"]')

    def test_doctor_reports_missing_key_without_network(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            stdout = io.StringIO()
            stderr = io.StringIO()
            env = {"DEERFLOW_SESSION_DB": str(Path(temp_dir) / "sessions.sqlite3")}
            with patch.dict(os.environ, env, clear=True), redirect_stdout(stdout), redirect_stderr(stderr):
                exit_code = cli.main(["doctor"])

        report = json.loads(stdout.getvalue())
        self.assertEqual(exit_code, 2)
        self.assertEqual(report["status"], "missing_api_key")
        self.assertFalse(report["api_key_configured"])
        self.assertFalse(report["network_checked"])
        self.assertEqual(stderr.getvalue(), "")

    def test_doctor_never_prints_configured_secret(self):
        secret = "df_open_cli_secret"
        stdout = io.StringIO()
        with patch.dict(os.environ, {"DEERFLOW_OPEN_API_KEY": secret}, clear=True), redirect_stdout(stdout):
            exit_code = cli.main(["doctor"])

        self.assertEqual(exit_code, 0)
        self.assertTrue(json.loads(stdout.getvalue())["api_key_configured"])
        self.assertNotIn(secret, stdout.getvalue())

    def test_show_session_does_not_require_api_key(self):
        with tempfile.TemporaryDirectory() as temp_dir:
            db_path = Path(temp_dir) / "sessions.sqlite3"
            with SQLiteSessionStore(db_path) as store:
                store.put(
                    conversation_id="conversation-001",
                    session_id="open_sess_123",
                    external_subject_id="customer-001",
                    metadata={"source": "unittest"},
                )
            stdout = io.StringIO()
            with patch.dict(os.environ, {}, clear=True), redirect_stdout(stdout):
                exit_code = cli.main(
                    [
                        "--session-db",
                        str(db_path),
                        "show-session",
                        "--conversation-id",
                        "conversation-001",
                    ]
                )

        self.assertEqual(exit_code, 0)
        self.assertEqual(json.loads(stdout.getvalue())["session_id"], "open_sess_123")

    def test_poll_timeout_is_bounded(self):
        class AlwaysRunningService:
            def get_run(self, conversation_id, run_id):
                return {"run_id": run_id, "status": "running"}

        with patch("agent_integration.__main__.time.monotonic", side_effect=[0.0, 2.0]):
            with redirect_stdout(io.StringIO()), self.assertRaises(TimeoutError):
                cli._poll_run(  # pylint: disable=protected-access
                    AlwaysRunningService(),  # type: ignore[arg-type]
                    "conversation-001",
                    "run-001",
                    poll_interval=0.1,
                    poll_timeout=1.0,
                )

    def test_successful_poll_without_final_content_emits_warning(self):
        class SuccessfulService:
            def get_run(self, conversation_id, run_id):
                return {
                    "run_id": run_id,
                    "status": "success",
                    "final_content": None,
                }

        stdout = io.StringIO()
        stderr = io.StringIO()
        with redirect_stdout(stdout), redirect_stderr(stderr):
            cli._poll_run(  # pylint: disable=protected-access
                SuccessfulService(),  # type: ignore[arg-type]
                "conversation-001",
                "run-001",
                poll_interval=0.1,
                poll_timeout=1.0,
            )

        self.assertEqual(json.loads(stdout.getvalue())["status"], "success")
        warning = json.loads(stderr.getvalue())
        self.assertEqual(warning["warning"], "run_result_unavailable")
        self.assertEqual(warning["run_id"], "run-001")


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