import csv
import os
import re
from datetime import datetime
from django.conf import settings

from tournaments.models.enums import FederalCategory

def clean_licence_id(licence_id):
    # This regex matches the trailing letters (non-digits) and removes them
    cleaned_licence_id = re.sub(r'\D+$', '', str(licence_id))  # \D+ matches non-digits at the end
    return cleaned_licence_id.lstrip("0")

def get_player_name_from_csv(category, licence_id, base_folder=None):
    """
    Search for a player's first name, last name, and rank in the most recent rankings file.

    :param licence_id: The licence ID to search for.
    :param base_folder: Base folder containing the rankings folder.
    :return: A tuple (first_name, last_name, rank) or (None, None, None) if not found.
    """
    if base_folder is None:
        base_folder = settings.STATIC_ROOT

    folder_path = os.path.join(base_folder, "rankings")

    if licence_id:
        cleaned_licence_id = clean_licence_id(licence_id)
    else:
        cleaned_licence_id = None

    print("get_player_name_from_csv", cleaned_licence_id)

    def extract_date(file_name):
        """
        Extract the date (MM-YYYY) from the file name and return it as a datetime object.
        """
        match = re.search(r"(\d{2}-\d{4})", file_name)
        if match:
            return datetime.strptime(match.group(1), "%m-%Y")
        return None

    def find_most_recent_file(file_type):
        """
        Find the most recent file for the given type (-MESSIEURS- or -DAMES-).
        """
        files = [
            f for f in os.listdir(folder_path)
            if file_type in f and re.search(r"\d{2}-\d{4}", f)
        ]
        files_with_dates = [(f, extract_date(f) or datetime.min) for f in files]
        if not files_with_dates:
            return None
        # Sort by date in descending order
        files_with_dates.sort(key=lambda x: x[1], reverse=True)
        return os.path.join(folder_path, files_with_dates[0][0])

    def search_file(file_path, is_woman):
        if not file_path or not os.path.exists(file_path):
            print("no file found")
            return None, False

        last_rank = None
        last_rank_count = 0
        with open(file_path, newline='', encoding='utf-8') as file:
            reader = csv.reader(file, delimiter=';')
            rows = list(reader)  # Read all rows at once to process later


            if cleaned_licence_id:
                for row in rows:
                    if len(row) >= 15:  # Ensure row has enough columns
                        current_licence_id = row[5]
                        if current_licence_id == str(cleaned_licence_id):
                            data = {
                                "first_name": row[3],  # 4th column: first name
                                "last_name": row[2],   # 3rd column: last name
                                "rank": row[1],
                                "points": row[6],
                                "assimilation": row[7],
                                "tournament_count": row[8],
                                "ligue_name": row[9],
                                "club_name": row[11],
                                "birth_year": row[14],
                                "is_woman": is_woman,
                            }
                            return data, True

            # Determine the rank for an unranked player
            if rows:
                # Find the last rank in the file
                last_row = rows[-1]
                if len(last_row) >= 2:
                    last_rank = last_row[1]

                # Count how many times the last rank appears
                last_rank_count = sum(1 for row in rows if len(row) >= 2 and row[1] == last_rank)

        if last_rank is not None:
            unranked_rank = int(last_rank) + last_rank_count + 1
            data = {
                "rank": str(unranked_rank),
                "is_woman": is_woman
            }
            return data, False

        return None, False


    dames_file = find_most_recent_file("CLASSEMENT-PADEL-DAMES-")
    result, found = search_file(dames_file, True)
    if found or category is FederalCategory.WOMEN:
        return result, found

    messieurs_file = find_most_recent_file("CLASSEMENT-PADEL-MESSIEURS-")
    result, found = search_file(messieurs_file, False)
    return result, found
