#include "api.hh"
#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

#define Map vector<vector<etat_case>> 


struct EPosition{  // Enhanced position
    int colonne;
    int ligne;
    int niveau;
    position mama_pos;

    bool operator<(const EPosition& other){
        int diffx = (colonne - mama_pos.colonne), diffy = (ligne - mama_pos.ligne);
        int dist_sq = diffx * diffx + diffy * diffy;

        int other_diffx = (other.colonne - other.mama_pos.colonne), other_diffy = (other.ligne - other.mama_pos.ligne);
        int other_dist_sq = other_diffx * other_diffx + other_diffy * other_diffy;
        return dist_sq < other_dist_sq;
    }
};


#pragma region Constantes
const int CONQUETE_NIDS = 0;
const int RECHERCHE_PAIN = 1;
const int NEST_SEARCH_TURN_LIMIT = 41;
const int OPTIMAL_LENGTH = 10;
const vector<pair<int, int>> DIR = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
#pragma endregion

#pragma region Variables
int player_id, opponent_id;
vector<position> nids(0);
vector<position> nids_obtenus(0);
vector<position> trous(0);
int current_phase;
map<int, vector<direction>> paths;
map<int, position> aim2;
map<direction, pair<int, int>> MDIR;
vector<position> blacklist_cases(0); 
#pragma endregion


vector<position> sort_by_distance(vector<position>& pos, position& mama_pos){
    
    vector<EPosition> ep(pos.size());
    for(int i = 0; i < pos.size(); i++){
        ep.at(i) = {pos.at(i).colonne, pos.at(i).ligne, pos.at(i).niveau, mama_pos};
    }

    sort(ep.begin(), ep.end());

    vector<position> ret(pos.size());
    for(int i = 0; i < pos.size(); i++){
        ret.at(i) = {ep.at(i).colonne, ep.at(i).ligne, ep.at(i).niveau};
    }
    return ret;
}

// Fonction appelée au début de la partie.
void partie_init(void)
{
    player_id = moi();
    opponent_id = adversaire();
    current_phase = CONQUETE_NIDS;
    MDIR[NORD] = make_pair(0, 1);
    MDIR[SUD] = make_pair(0, -1);
    MDIR[EST] = make_pair(1, 0);
    MDIR[OUEST] = make_pair(-1, 0);


    for(troupe tr : troupes_joueur(player_id)){
        paths[tr.id] = vector<direction>(0);
    }

    #pragma region Charge la carte
    for(int y = 0; y < HAUTEUR; y++){
        for(int x = 0; x < LARGEUR; x++){
            position pos = {y, x, 0};
            // ajoute au tableau si c'est un nid
            if(info_case(pos).contenu == NID){
                nids.push_back(pos);
            }else if(info_case(pos).contenu == TROU){
                trous.push_back(pos);
            }
        }
    }
    #pragma endregion
}


vector<pair<int, int>> cote(const direction& cur_dir){
    vector<pair<int, int>> ret(0);
    for(pair<int, int> p : DIR){
        if(p.first * MDIR[cur_dir].first + p.second * MDIR[cur_dir].second == 0){  // Produit scalaire
            ret.push_back(p);
        }
    }
    return ret;
}


void debug_path(const troupe& tr, const vector<direction>& path){

    pair<int, int> pos = make_pair(tr.maman.colonne, tr.maman.ligne);
    for(direction dir : path){
        pos.first += MDIR[dir].first;
        pos.second += MDIR[dir].second;
        position tmp = {pos.first, pos.second, tr.maman.niveau};
        debug_poser_pigeon(tmp, PIGEON_ROUGE);
    }
}


troupe get_troupe_by_id(int id){
    for(troupe trp_ : troupes_joueur(player_id)){
        if(trp_.id == id) return trp_;
    }
}


bool is_in_troop(const troupe& tr, const position& target){
    for(position pos : tr.canards){
        if(pos == target) return true;
    }

    return false;
}


void update_nests(){
    nids_obtenus.clear();
    for(position nest_pos : nids){
        etat_nid etat = info_nid(nest_pos);
        if(etat == player_id + 1){
            nids_obtenus.push_back(nest_pos);
        }
    }
}


bool is_the_ennemy_killable(const troupe& adv_troupe){  // si les 2 cotes de l'adversaire sont non traversables
    vector<pair<int, int>> cotes_adv = cote(adv_troupe.dir);
    for(pair<int, int> p : cotes_adv){
        position tmp_pos = {adv_troupe.maman.colonne + p.first, adv_troupe.maman.ligne + p.second, adv_troupe.maman.niveau};
        debug_poser_pigeon(tmp_pos, PIGEON_ROUGE);
        etat_case etat = info_case(tmp_pos);
        type_case stat_tmp = etat.contenu;
        if(!(stat_tmp == BUISSON || (stat_tmp == BARRIERE && info_barriere(tmp_pos) == FERMEE))){
            return false;
        }
    }
    return true;
}


int go2target(const troupe& tr, const vector<position>& target_list, int pts=PTS_ACTION){  // Renvoie les pts restants
    debug_poser_pigeon(tr.maman, PIGEON_JAUNE);
    troupe cur_tr = get_troupe_by_id(tr.id);
    int action_pt = pts;
    
    for(position target_pos : target_list){
        int used = 0;

        if(is_in_troop(cur_tr, target_pos) ){
            continue;
        }
        
        // Verifie si la case est deja visee par un autre troupe de ce joueur.
        bool nxt = false;
        for (auto it = aim2.begin(); it != aim2.end(); ++it) {
            if(it -> first != tr.id && it -> second == target_pos){
                nxt = true;
                break;
            }
        } 
        if(nxt) continue;


        vector<direction> path = trouver_chemin(cur_tr.maman, target_pos);
        // debug_path(cur_tr, path);

        position prev_mama_pos = cur_tr.maman;
        erreur can_continue = OK;
        
        // avance
        if(path.size() > 0){
            aim2[tr.id] = target_pos;
            // debug_poser_pigeon(target_pos, PIGEON_BLEU);
        }
        while(can_continue == OK && path.size() > 0){
            can_continue = avancer(cur_tr.id, path.at(0));
            path.erase(path.begin());
            action_pt--;
            used++;
        }
        cur_tr = get_troupe_by_id(cur_tr.id);
    }


    return action_pt;
}

void jouer_tour(void)
{
    for(troupe tr : troupes_joueur(player_id)){
        avancer(tr.id, EST);
        avancer(tr.id, EST);
        avancer(tr.id, EST);
        position tunnel = {3, 14, -1};
        creuser_tunnel(tunnel);
        avancer(tr.id, BAS);        
    }
}

// Fonction appelée à la fin de la partie.
void partie_fin(void)
{
    // TODO
    
    
}