"""
Sprint 0 — sanity: un Project recién creado se guarda y se carga sin pérdida.
"""

from __future__ import annotations

from pathlib import Path

import pytest

from arelec.core.project import Project, ProjectMetadata, SCHEMA_VERSION


def test_project_default_metadata() -> None:
    p = Project()
    assert p.metadata.name == "Nuevo proyecto"
    assert p.metadata.schema_version == SCHEMA_VERSION
    assert p.metadata.created_at != ""


def test_save_and_load_roundtrip(tmp_path: Path) -> None:
    path = tmp_path / "demo.area"
    original = Project(metadata=ProjectMetadata(
        name="Yate Demo",
        author="ARD",
        company="AR ShipDesign",
        notes="Sprint 0 test",
    ))
    original.save(path)
    assert path.exists()
    assert path.stat().st_size > 0

    loaded = Project.load(path)
    assert loaded.metadata.name == "Yate Demo"
    assert loaded.metadata.author == "ARD"
    assert loaded.metadata.company == "AR ShipDesign"
    assert loaded.metadata.notes == "Sprint 0 test"
    assert loaded.metadata.schema_version == SCHEMA_VERSION


def test_save_touches_modified_at(tmp_path: Path) -> None:
    p = Project()
    original_modified = p.metadata.modified_at
    p.save(tmp_path / "t.area")
    # Save siempre actualiza modified_at (aunque sea el mismo segundo, queda con
    # nueva timestamp ISO — comparamos que fue tocado).
    assert p.metadata.modified_at >= original_modified


def test_load_rejects_future_schema(tmp_path: Path) -> None:
    """Un .area creado por una versión más nueva debe rechazarse limpio."""
    path = tmp_path / "future.area"
    p = Project(metadata=ProjectMetadata(schema_version=SCHEMA_VERSION + 99))
    p.save(path)
    with pytest.raises(ValueError, match="schema_version"):
        Project.load(path)


def test_load_rejects_missing_project_json(tmp_path: Path) -> None:
    import zipfile

    path = tmp_path / "empty.area"
    with zipfile.ZipFile(path, mode="w") as zf:
        zf.writestr("readme.txt", "no project.json")
    with pytest.raises(KeyError):
        Project.load(path)


def test_load_rejects_non_zip(tmp_path: Path) -> None:
    import zipfile

    path = tmp_path / "garbage.area"
    path.write_bytes(b"this is not a zip file")
    with pytest.raises(zipfile.BadZipFile):
        Project.load(path)
