from __future__ import annotations

import os
import tempfile
import unittest
from pathlib import Path

import doc2md.cli as cli
from doc2md import history_db


class UiActionsTest(unittest.TestCase):
    def test_ui_diff_for_run(self) -> None:
        with tempfile.TemporaryDirectory() as tmpdir:
            base = Path(tmpdir)
            input_path = base / "sample.csv"
            output_path = base / "sample.csv.md"
            input_path.write_text("a,b\n1,2\n", encoding="utf-8")
            output_path.write_text("old", encoding="utf-8")

            db_path = base / "history.db"
            logger = history_db.HistoryLogger(db_path)
            run_id = logger.start_run(
                engine="pdfminer",
                fmt="csv",
                options={},
                cwd=str(base),
                version="test",
            )
            logger.add_input(
                run_id,
                path=input_path,
                sha256=history_db.sha256_file(input_path),
                size_bytes=input_path.stat().st_size,
                mtime_ns=input_path.stat().st_mtime_ns,
            )
            logger.add_output(
                run_id,
                path=output_path,
                bytes_len=output_path.stat().st_size,
                sha256=history_db.sha256_file(output_path),
                written=True,
            )
            logger.finish_run(run_id, status="success", exit_code=0)
            logger.close()

            run = history_db.load_run(db_path, run_id)
            assert run is not None
            diff_lines = cli._ui_diff_for_run(run)
            joined = "\n".join(diff_lines)
            self.assertIn("---", joined)
            self.assertIn("+++", joined)


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