"""Tests for ``arautopilot.core.project_config``."""

from __future__ import annotations

from pathlib import Path

import pytest
from pydantic import ValidationError

from arautopilot.core import ProjectConfig


def test_project_has_required_fields(basic_project: ProjectConfig) -> None:
    assert basic_project.project_id
    assert basic_project.client_name
    assert basic_project.project_name
    assert basic_project.vessel is not None
    assert basic_project.schema_version == "0.1.0"


def test_to_dict_is_json_safe(basic_project: ProjectConfig) -> None:
    import json
    d = basic_project.to_dict()
    # json.dumps would raise on raw datetimes; model_dump(mode="json") avoids that.
    encoded = json.dumps(d)
    assert "project_id" in encoded


def test_round_trip_json(basic_project: ProjectConfig) -> None:
    text = basic_project.to_json()
    rebuilt = ProjectConfig.from_json(text)
    assert rebuilt == basic_project


def test_round_trip_yaml(basic_project: ProjectConfig) -> None:
    text = basic_project.to_yaml()
    rebuilt = ProjectConfig.from_yaml(text)
    assert rebuilt == basic_project


def test_save_and_load_yaml(tmp_path: Path, basic_project: ProjectConfig) -> None:
    out = tmp_path / "project.yaml"
    basic_project.save_yaml(out)
    rebuilt = ProjectConfig.load(out)
    assert rebuilt == basic_project


def test_save_and_load_json(tmp_path: Path, basic_project: ProjectConfig) -> None:
    out = tmp_path / "project.json"
    basic_project.save_json(out)
    rebuilt = ProjectConfig.load(out)
    assert rebuilt == basic_project


def test_load_rejects_unknown_extension(tmp_path: Path, basic_project: ProjectConfig) -> None:
    bogus = tmp_path / "project.toml"
    bogus.write_text("# nothing", encoding="utf-8")
    with pytest.raises(ValueError):
        ProjectConfig.load(bogus)


def test_rejects_unknown_top_level_field(basic_project: ProjectConfig) -> None:
    d = basic_project.to_dict()
    d["surprise"] = "value"
    with pytest.raises(ValidationError):
        ProjectConfig.from_dict(d)


def test_touch_updates_modified_at(basic_project: ProjectConfig) -> None:
    original = basic_project.modified_at
    bumped = basic_project.touch()
    assert bumped.modified_at >= original
    assert bumped.project_id == basic_project.project_id
