#include <stddef.h>
#include <stdbool.h>
#include "play.h"

bool valid_play(Hand *field, Card *played, Card *target) {
  if (target == NULL) {
    bool matching_month_in_field = false;
    for (int i = 0; i < field->count; i++) {
      if (field->cards[i]->month == played->month) {
	matching_month_in_field = true;
	break;
      }
    }
    return !matching_month_in_field;
  } else {
    bool target_in_field = false;
    for (int i = 0; i < field->count; i++) {
      if (field->cards[i]->index == target->index) {
	target_in_field = true;
	break;
      }
    }
    if (!target_in_field) return false;
    return played->month == target->month;
  }
}

Card *valid_target(Card *active, Hand *field) {
  for (int i = 0; i < field->count; i++) {
    if (field->cards[i]->month == active->month) {
      return field->cards[i];
    }
  }

  return NULL;
}

Play ai_play(Hand *hand, Hand *field) {
  // very naive play initially
  Card *played = hand->cards[0];
  for (int i = 0; i < field->count; i++) {
    Card *target = field->cards[i];
    if (valid_play(field, played, target)) return (Play) { played, target };
  }
  return (Play) { played, NULL };
}
