from pathlib import Path

import pytest

from c2m_by_nery.core.converter import (
    convert_file_to_markdown,
    generate_frontmatter,
)


def test_generate_frontmatter_basic() -> None:
    git_meta = {"project": "myrepo", "branch": "main", "commit": "abc123"}
    result = generate_frontmatter("src/foo.py", Path("/repo/src/foo.py"), git_meta)

    assert result.startswith("---\n")
    assert "Project: myrepo" in result
    assert "Branch: main" in result
    assert "Commit: abc123" in result
    assert "Path: src/foo.py" in result
    assert "Link: file:" in result
    assert "---" in result


def test_generate_frontmatter_with_part() -> None:
    git_meta = {"project": "x", "branch": "b", "commit": "c"}
    result = generate_frontmatter(
        "big.py", Path("/repo/big.py"), git_meta, part=1
    )
    assert "Path: big.py (part 2)" in result


def test_generate_frontmatter_with_part_and_total() -> None:
    git_meta = {"project": "x", "branch": "b", "commit": "c"}
    result = generate_frontmatter(
        "backstage-d86ff698d-bt7gl_backstage.log",
        Path("/repo/backstage-d86ff698d-bt7gl_backstage.log"),
        git_meta,
        part=2,
        total_parts=6,
    )
    assert "Path: backstage-d86ff698d-bt7gl_backstage.log (part 3/6)" in result


def test_generate_frontmatter_no_frontmatter() -> None:
    git_meta = {"project": "x", "branch": "b", "commit": "c"}
    result = generate_frontmatter(
        "x.py", Path("/x.py"), git_meta, include_frontmatter=False
    )
    assert result == ""


def test_generate_frontmatter_missing_git_meta() -> None:
    result = generate_frontmatter("x.py", Path("/x.py"), {})
    assert "Project: unknown" in result
    assert "Branch: unknown" in result
    assert "Commit: unknown" in result


def test_convert_file_to_markdown_plain_text(tmp_path: Path) -> None:
    py_file = tmp_path / "test.py"
    py_file.write_text("print('hello')")

    result = convert_file_to_markdown(py_file)
    assert result.startswith("```python\n")
    assert "print('hello')" in result
    assert result.endswith("\n```")


def test_convert_file_to_markdown_unknown_extension(tmp_path: Path) -> None:
    file = tmp_path / "unknown.xyz"
    file.write_text("some content")

    result = convert_file_to_markdown(file)
    assert "```text\n" in result
    assert "some content" in result


def test_convert_file_to_markdown_markdown_via_docling(tmp_path: Path) -> None:
    md_file = tmp_path / "readme.md"
    md_file.write_text("# Title\n\nParagraph with **bold**.")

    result = convert_file_to_markdown(md_file)
    assert "Title" in result
    assert "Paragraph" in result or "bold" in result
