import requests
import csv
import os
from datetime import datetime


def get_comp_info(params, headers, logging):
    def get_battlegrounds_comp_stats():
        url = "https://hsreplay.net/analytics/query/battlegrounds_comp_stats/"
        response = requests.get(url, params=params, headers=headers)
        if response.status_code == 200:
            json_response = response.json()
            data = json_response["series"]["data"]
            return data
        else:
            logging.error(f"请求失败，状态码: {response.status_code}")

    def get_compositions():
        url = "https://hsreplay.net/api/v1/battlegrounds/compositions/"
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            json_response = response.json()
            data = json_response
            return data
        else:
            logging.error(f"请求失败，状态码: {response.status_code}")

    comp_stats = get_battlegrounds_comp_stats()
    compositions = get_compositions()

    mapping = {}
    for entry in compositions:
        mapping[entry["id"]] = entry["name"]
    modified_compositions = []
    for entry in comp_stats:
        friendly_composition = entry["friendly_composition"]
        name = mapping.get(friendly_composition)
        new_entry = {
            "ID": friendly_composition,
            "Name": name,
            "Avg_Final_Placement": entry["avg_final_placement"],
            "Final_Placement_Distribution":
            entry["final_placement_distribution"],
            "Popularity": entry["popularity"]
        }
        modified_compositions.append(new_entry)

    output_directory = "output/compositions"
    current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
    csv_filename = f"{current_time}.csv"
    csv_output_file = os.path.join(output_directory, csv_filename)
    os.makedirs(output_directory, exist_ok=True)

    fieldnames = [
        "ID", "Name", "Avg_Final_Placement", "Final_Placement_Distribution",
        "Popularity"
    ]

    with open(csv_output_file, mode="w", newline="",
              encoding="utf-8") as outfile:
        csv_writer = csv.DictWriter(outfile, fieldnames=fieldnames)
        csv_writer.writeheader()
        csv_writer.writerows(modified_compositions)