#ifndef KOTH_AXELROD_BOT_CLIENT_HPP
#define KOTH_AXELROD_BOT_CLIENT_HPP

// Protocol-v6 C++17 client for the six-action Axelrod arena (POSIX sockets).
// Keep this file beside your .cpp strategy. Only choose_action needs editing.

#include <cerrno>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <netdb.h>
#include <netinet/tcp.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <sys/socket.h>
#include <thread>
#include <unistd.h>
#include <vector>

namespace koth {

enum class Action { Cooperate, Betray, Defend, Punish, Sabotage, Siege, Resign };

inline const char* action_name(Action action) {
    switch (action) {
        case Action::Cooperate: return "COOPERATE";
        case Action::Betray: return "BETRAY";
        case Action::Defend: return "DEFEND";
        case Action::Punish: return "PUNISH";
        case Action::Sabotage: return "SABOTAGE";
        case Action::Siege: return "SIEGE";
        case Action::Resign: return "R";
    }
    throw std::runtime_error("unknown action");
}

inline Action parse_action(const std::string& word) {
    for (Action action : {Action::Cooperate, Action::Betray, Action::Defend,
                          Action::Punish, Action::Sabotage, Action::Siege}) {
        if (word == action_name(action)) return action;
    }
    throw std::runtime_error("invalid action from server: " + word);
}

struct RoundResult {
    int number = 0;
    Action mine = Action::Cooperate;
    Action opponent = Action::Cooperate;
    int my_points = 0;
    int opponent_points = 0;
    int my_score = 0;
    int opponent_score = 0;
};

struct MatchState {
    std::string my_id;
    std::string match_id;
    std::string opponent_id;
    std::string opponent_name;
    int round = 0;
    int my_score = 0;
    int opponent_score = 0;
    std::vector<RoundResult> history;
};

using Strategy = Action (*)(const MatchState&);

inline std::vector<std::string> words(const std::string& line) {
    std::istringstream stream(line);
    std::vector<std::string> result;
    std::string word;
    while (stream >> word) result.push_back(word);
    return result;
}

inline int number(const std::string& word) {
    std::size_t consumed = 0;
    int value = 0;
    try { value = std::stoi(word, &consumed); }
    catch (const std::exception&) { throw std::runtime_error("invalid number: " + word); }
    if (consumed != word.size()) throw std::runtime_error("invalid number: " + word);
    return value;
}

inline bool valid_name(const std::string& name) {
    if (name.empty() || name.size() > 32) return false;
    for (unsigned char ch : name) {
        if (!((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z') ||
              (ch >= '0' && ch <= '9') || ch == '_' || ch == '.' || ch == '-')) return false;
    }
    return true;
}

class Connection {
public:
    Connection(const std::string& host, const std::string& port) {
        addrinfo hints{};
        hints.ai_family = AF_UNSPEC;
        hints.ai_socktype = SOCK_STREAM;
        addrinfo* addresses = nullptr;
        const int lookup = ::getaddrinfo(host.c_str(), port.c_str(), &hints, &addresses);
        if (lookup != 0) throw std::runtime_error(::gai_strerror(lookup));
        for (addrinfo* address = addresses; address; address = address->ai_next) {
            const int candidate = ::socket(address->ai_family, address->ai_socktype, address->ai_protocol);
            if (candidate < 0) continue;
            int enabled = 1;
            (void)::setsockopt(candidate, IPPROTO_TCP, TCP_NODELAY, &enabled, sizeof(enabled));
            if (::connect(candidate, address->ai_addr, address->ai_addrlen) == 0) {
                fd_ = candidate;
                break;
            }
            ::close(candidate);
        }
        ::freeaddrinfo(addresses);
        if (fd_ < 0) throw std::runtime_error("could not connect to " + host + ":" + port);
    }

    Connection(const Connection&) = delete;
    Connection& operator=(const Connection&) = delete;
    ~Connection() { if (fd_ >= 0) ::close(fd_); }

    void send_line(const std::string& line) {
        const std::string payload = line + "\n";
        std::size_t sent = 0;
        while (sent < payload.size()) {
#ifdef MSG_NOSIGNAL
            const int flags = MSG_NOSIGNAL;
#else
            const int flags = 0;
#endif
            const ssize_t size = ::send(fd_, payload.data() + sent, payload.size() - sent, flags);
            if (size < 0 && errno == EINTR) continue;
            if (size <= 0) throw std::runtime_error("socket send failed");
            sent += static_cast<std::size_t>(size);
        }
    }

    bool read_line(std::string& line) {
        while (true) {
            const std::size_t newline = buffer_.find('\n');
            if (newline != std::string::npos) {
                line = buffer_.substr(0, newline);
                buffer_.erase(0, newline + 1);
                if (!line.empty() && line.back() == '\r') line.pop_back();
                return true;
            }
            if (buffer_.size() > 4096) throw std::runtime_error("server line too long");
            char chunk[1024];
            const ssize_t received = ::recv(fd_, chunk, sizeof(chunk), 0);
            if (received < 0 && errno == EINTR) continue;
            if (received < 0) throw std::runtime_error("socket receive failed");
            if (received == 0) return false;
            buffer_.append(chunk, static_cast<std::size_t>(received));
        }
    }

private:
    int fd_ = -1;
    std::string buffer_;
};

inline int run_bot(int argc, char** argv, Strategy choose_action) {
    if (argc != 4 || !valid_name(argv[1])) {
        std::cerr << "Usage: KOTH_BOT_TOKEN=... " << argv[0] << " BotName host port\n";
        return 2;
    }
    const char* token = std::getenv("KOTH_BOT_TOKEN");
    if (!token || !*token) {
        std::cerr << "Set KOTH_BOT_TOKEN to your arena token.\n";
        return 2;
    }
    const std::string name = argv[1];
    const std::string host = argv[2];
    const std::string port = argv[3];
    while (true) {
        try {
            Connection connection(host, port);
            connection.send_line("HELLO 6 " + name + " " + token);
            MatchState state;
            std::string line;
            while (connection.read_line(line)) {
                const auto part = words(line);
                if (part.empty()) continue;
                if (part[0] == "WELCOME" && part.size() == 3 && part[1] == "6") {
                    state.my_id = part[2];
                    std::cout << "Connected as " << state.my_id << std::endl;
                } else if (part[0] == "MATCH_START" && part.size() == 4) {
                    state.match_id = part[1];
                    state.opponent_id = part[2];
                    state.opponent_name = part[3];
                    state.round = 0;
                    state.my_score = state.opponent_score = 0;
                    state.history.clear(); // Reconnection replay rebuilds this match.
                    std::cout << "Match " << state.match_id << " vs " << state.opponent_name << std::endl;
                } else if (part[0] == "ROUND_RESULT" && part.size() == 8) {
                    state.history.push_back(RoundResult{
                        number(part[1]), parse_action(part[2]), parse_action(part[3]),
                        number(part[4]), number(part[5]), number(part[6]), number(part[7])});
                } else if (part[0] == "ROUND" && part.size() == 5) {
                    if (part[1] != state.match_id) throw std::runtime_error("unexpected match ID");
                    state.round = number(part[2]);
                    state.my_score = number(part[3]);
                    state.opponent_score = number(part[4]);
                    const Action action = choose_action(state);
                    connection.send_line(action == Action::Resign ? "R" :
                                         std::string("MOVE ") + action_name(action));
                } else if (part[0] == "END" && part.size() == 6) {
                    std::cout << line << std::endl;
                    connection.send_line("Q");
                } else if (part[0] == "ERROR") {
                    // Credential/name problems cannot fix themselves: stop. Anything else
                    // (bot_already_connected while the server drops a stale socket,
                    // hello_timeout, server_error, ...) is temporary: reconnect.
                    if (line.find("invalid_token") != std::string::npos ||
                        line.find("token_revoked") != std::string::npos ||
                        line.find("name_already_registered") != std::string::npos ||
                        line.find("invalid_bot_name") != std::string::npos) {
                        std::cerr << "Arena rejected credentials: " << line << std::endl;
                        return 1;
                    }
                    throw std::runtime_error("arena error: " + line);
                } else {
                    throw std::runtime_error("unexpected server message: " + line);
                }
            }
        } catch (const std::exception& error) {
            std::cerr << "Connection lost (" << error.what() << "); retrying\n";
        }
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

} // namespace koth

#endif
