from __future__ import annotations

import argparse
import os
import tempfile
import threading
import unittest
from pathlib import Path

import doc2md.cli as cli
from doc2md import history_db


class SlashHistoryCommandTest(unittest.TestCase):
    def _make_args(self) -> argparse.Namespace:
        return argparse.Namespace(
            format=None,
            engine="pdfminer",
            output=None,
            theme="auto",
            quiet=True,
            debug=False,
            csv_na="",
            csv_float_format=None,
        )

    def test_history_slash_command_renders_output(self) -> None:
        try:
            from prompt_toolkit.input.defaults import create_pipe_input
            from prompt_toolkit.output import DummyOutput
        except Exception:
            self.skipTest("prompt_toolkit not installed")

        with tempfile.TemporaryDirectory() as tmpdir:
            db_path = Path(tmpdir) / "history.db"
            backup = os.environ.get("DOC2MD_HISTORY_DB")
            os.environ["DOC2MD_HISTORY_DB"] = str(db_path)

            try:
                logger = history_db.HistoryLogger(db_path)
                run_id = logger.start_run(
                    engine="pdfminer",
                    fmt=None,
                    options={},
                    cwd=str(Path(tmpdir)),
                    version="test",
                )
                logger.finish_run(run_id, status="success", exit_code=0)
                logger.close()

                args = self._make_args()

                def debug(_msg: str) -> None:
                    return

                with create_pipe_input() as pipe_input:
                    app, state = cli._build_interactive_app(
                        args,
                        debug,
                        input=pipe_input,
                        output=DummyOutput(),
                    )

                    def feed() -> None:
                        pipe_input.send_text("/more history")
                        pipe_input.send_text("\r")
                        pipe_input.send_text("\x1b")

                    thread = threading.Thread(target=feed)
                    thread.start()
                    app.run()
                    thread.join()

                joined = "\n".join(state["output_lines"])
                self.assertIn(str(run_id), joined)
            finally:
                if backup is None:
                    os.environ.pop("DOC2MD_HISTORY_DB", None)
                else:
                    os.environ["DOC2MD_HISTORY_DB"] = backup


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