import pytest
from typing import Any
import json
from src.project_manager import get_all_tracks, save_track_state
from src.models import TrackState, Metadata, Ticket
from datetime import datetime

def test_get_all_tracks_empty(tmp_path: Any) -> None:
 assert get_all_tracks(tmp_path) == []

def test_get_all_tracks_with_state(tmp_path: Any) -> None:
 tracks_dir = tmp_path / "conductor" / "tracks"
 tracks_dir.mkdir(parents=True)
 track_id = "test_track_1"
 track_dir = tracks_dir / track_id
 track_dir.mkdir()
 # Create TrackState
 metadata = Metadata(id=track_id, name="Test Track 1", status="in_progress", 
  created_at=datetime.now(), updated_at=datetime.now())
 tasks = [
  Ticket(id="task1", description="desc1", status="completed", assigned_to="user"),
  Ticket(id="task2", description="desc2", status="todo", assigned_to="user")
 ]
 state = TrackState(metadata=metadata, discussion=[], tasks=tasks)
 save_track_state(track_id, state, tmp_path)
 tracks = get_all_tracks(tmp_path)
 assert len(tracks) == 1
 track = tracks[0]
 assert track["id"] == track_id
 assert track["title"] == "Test Track 1"
 assert track["status"] == "in_progress"
 assert track["complete"] == 1
 assert track["total"] == 2
 assert track["progress"] == 0.5

def test_get_all_tracks_with_metadata_json(tmp_path: Any) -> None:
 tracks_dir = tmp_path / "conductor" / "tracks"
 tracks_dir.mkdir(parents=True)
 track_id = "test_track_2"
 track_dir = tracks_dir / track_id
 track_dir.mkdir()
 metadata = {
  "id": track_id,
  "title": "Test Track 2",
  "status": "planned"
 }
 with open(track_dir / "metadata.json", "w") as f:
  json.dump(metadata, f)
  # Create plan.md to test parsing
 plan_content = """
# Plan
- [x] Task: Task 1
- [ ] Task: Task 2
- [~] Task: Task 3
"""
 with open(track_dir / "plan.md", "w") as f:
  f.write(plan_content)
 tracks = get_all_tracks(tmp_path)
 assert len(tracks) == 1
 track = tracks[0]
 assert track["id"] == track_id
 assert track["title"] == "Test Track 2"
 assert track["status"] == "planned"
 assert track["complete"] == 1
 assert track["total"] == 3
 assert pytest.approx(track["progress"]) == 0.333333

def test_get_all_tracks_malformed(tmp_path: Any) -> None:
 tracks_dir = tmp_path / "conductor" / "tracks"
 tracks_dir.mkdir(parents=True)
 track_id = "malformed_track"
 track_dir = tracks_dir / track_id
 track_dir.mkdir()
 # Malformed metadata.json
 with open(track_dir / "metadata.json", "w") as f:
  f.write("{ invalid json }")
 tracks = get_all_tracks(tmp_path)
 assert len(tracks) == 1
 track = tracks[0]
 assert track["id"] == track_id
 assert track["status"] == "unknown"
 assert track["complete"] == 0
 assert track["total"] == 0
