import subprocess
import json


def get_message_content(stdout):
 for line in stdout.splitlines():
  line = line.strip()
  if not line:
   continue
  try:
   obj = json.loads(line)
   if isinstance(obj, dict) and obj.get('type') == 'message':
    return obj.get('content', '')
  except json.JSONDecodeError:
   continue
 return ''


def run_mock(prompt):
 return subprocess.run(
  ['uv', 'run', 'python', 'tests/mock_gemini_cli.py'],
  input=prompt,
  capture_output=True,
  text=True,
  cwd='.'
 )


def test_epic_prompt_returns_track_json():
 result = run_mock('PATH: Epic Initialization — please produce tracks')
 assert result.returncode == 0
 assert 'function_call' not in result.stdout
 content = get_message_content(result.stdout)
 parsed = json.loads(content)
 assert isinstance(parsed, list)
 assert len(parsed) > 0
 for item in parsed:
  assert 'id' in item
  assert 'title' in item


def test_sprint_prompt_returns_ticket_json():
 result = run_mock('Please generate the implementation tickets for this track.')
 assert result.returncode == 0
 assert 'function_call' not in result.stdout
 content = get_message_content(result.stdout)
 parsed = json.loads(content)
 assert isinstance(parsed, list)
 assert len(parsed) > 0
 for item in parsed:
  assert 'id' in item
  assert 'description' in item
  assert 'status' in item
  assert 'assigned_to' in item


def test_worker_prompt_returns_plain_text():
 result = run_mock('Please read test.txt\nYou are assigned to Ticket T1.\nTask Description: do something')
 assert result.returncode == 0
 assert 'function_call' not in result.stdout
 content = get_message_content(result.stdout)
 assert content != ''


def test_tool_result_prompt_returns_plain_text():
 result = run_mock('role: tool\nHere are the results: {"content": "done"}')
 assert result.returncode == 0
 content = get_message_content(result.stdout)
 assert content != ''
