import pytest
from pathlib import Path
from core.frontmatter import parse_frontmatter, write_frontmatter

SAMPLE_MD = """\
+++
title = "Test Article"
type = "Tech"
draft = false
tags = ["linux", "python"]
+++

# Body

Some content here.
"""

def test_parse_returns_frontmatter_dict(tmp_path):
    f = tmp_path / "index.md"
    f.write_text(SAMPLE_MD)
    fm, body = parse_frontmatter(f)
    assert fm["title"] == "Test Article"
    assert fm["type"] == "Tech"
    assert fm["draft"] is False
    assert "linux" in fm["tags"]

def test_parse_returns_body(tmp_path):
    f = tmp_path / "index.md"
    f.write_text(SAMPLE_MD)
    fm, body = parse_frontmatter(f)
    assert "# Body" in body
    assert "Some content here." in body

def test_write_preserves_format(tmp_path):
    f = tmp_path / "index.md"
    f.write_text(SAMPLE_MD)
    fm, body = parse_frontmatter(f)
    fm["title"] = "Updated Title"
    write_frontmatter(f, fm, body)
    fm2, _ = parse_frontmatter(f)
    assert fm2["title"] == "Updated Title"
    assert fm2["type"] == "Tech"

def test_write_is_idempotent(tmp_path):
    f = tmp_path / "index.md"
    f.write_text(SAMPLE_MD)
    fm, body = parse_frontmatter(f)
    write_frontmatter(f, fm, body)
    assert f.read_text() == SAMPLE_MD

def test_parse_raises_on_missing_delimiters(tmp_path):
    f = tmp_path / "index.md"
    f.write_text("# No frontmatter\n\nJust body.")
    with pytest.raises(ValueError, match="frontmatter"):
        parse_frontmatter(f)
