"""Tests for FileManager .skop/project.json management."""

import json
import tempfile
from pathlib import Path

from skop_runner.file_manager import FileManager


def test_read_project_id_missing_file():
    """No .skop/project.json → returns None."""
    with tempfile.TemporaryDirectory() as tmp:
        fm = FileManager(tmp)
        assert fm.get_project_id() is None


def test_write_and_read_project_id():
    """Write then read → returns correct ID."""
    with tempfile.TemporaryDirectory() as tmp:
        fm = FileManager(tmp)
        fm.write_skop_project_id("proj_abc123")
        assert fm.get_project_id() == "proj_abc123"

        # Verify file contents
        skop_file = Path(tmp) / ".skop" / "project.json"
        assert skop_file.exists()
        data = json.loads(skop_file.read_text())
        assert data["projectId"] == "proj_abc123"


def test_read_project_id_corrupt_json():
    """Invalid JSON → returns None, no crash."""
    with tempfile.TemporaryDirectory() as tmp:
        skop_dir = Path(tmp) / ".skop"
        skop_dir.mkdir()
        (skop_dir / "project.json").write_text("not valid json {{{")

        fm = FileManager(tmp)
        assert fm.get_project_id() is None


def test_read_project_id_missing_field():
    """{} (no projectId key) → returns None."""
    with tempfile.TemporaryDirectory() as tmp:
        skop_dir = Path(tmp) / ".skop"
        skop_dir.mkdir()
        (skop_dir / "project.json").write_text(json.dumps({"other": "value"}))

        fm = FileManager(tmp)
        assert fm.get_project_id() is None


def test_set_root_reads_existing_project_id():
    """Pre-existing .skop/project.json → auto-discovered on set_root."""
    with tempfile.TemporaryDirectory() as tmp:
        # Pre-create the file
        skop_dir = Path(tmp) / ".skop"
        skop_dir.mkdir()
        (skop_dir / "project.json").write_text(json.dumps({"projectId": "existing_id"}))

        fm = FileManager()
        fm.set_root(tmp)
        assert fm.get_project_id() == "existing_id"


def test_write_creates_skop_directory():
    """.skop/ dir created if missing."""
    with tempfile.TemporaryDirectory() as tmp:
        fm = FileManager(tmp)
        assert not (Path(tmp) / ".skop").exists()

        fm.write_skop_project_id("new_proj")
        assert (Path(tmp) / ".skop").is_dir()
        assert (Path(tmp) / ".skop" / "project.json").exists()


def test_write_overwrites_existing():
    """Writing a new projectId overwrites the old one."""
    with tempfile.TemporaryDirectory() as tmp:
        fm = FileManager(tmp)
        fm.write_skop_project_id("first")
        assert fm.get_project_id() == "first"

        fm.write_skop_project_id("second")
        assert fm.get_project_id() == "second"

        # Verify file on disk
        data = json.loads((Path(tmp) / ".skop" / "project.json").read_text())
        assert data["projectId"] == "second"
