#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar  4 07:58:12 2022

@author: nicolas
"""
from pathlib import Path
from typing import List, Dict
import re

from openpyxl import load_workbook
from websites_test_framework.tools import list2xlsx

# --------------------------
# PARAMETERS
# Les deux fichiers doivent être au format .xlsx
MANUAL_EVALUATIONS = "/home/nicolas/Travail/enseignements/S1/SAE/SAE105/SAE-105.xlsx"
AUTOMATIC_EVALUATIONS = "/home/nicolas/Travail/enseignements/S1/SAE/SAE105/scores.xlsx"
STUDENTS_WORKS = "/home/nicolas/Travail/enseignements/S1/SAE/SAE105/rendus"
OUTPUT_FILE = "/home/nicolas/Travail/enseignements/S1/SAE/SAE105/notes_finales_SAE105.xlsx"
MANUAL_EVALUATION_WEIGHT = 40
AUTOMATIC_EVALUATION_WEIGHT = 60
ROUND_NDIGITS = 2
# --------------------------


STUDENTS_WORKS = Path(STUDENTS_WORKS)


def xlsx2list(
    fichier_xlsx,
    sheet: int = 0,
    min_col: int = 1,
    max_col: int = 2**14,
    min_row: int = 1,
    max_row: int = 2**20,
) -> List[List]:
    """Return XLSX content as a list of lists.

    Column and lines indexes starts from 1 (and not 0).
    """
    wb = load_workbook(fichier_xlsx, data_only=True)
    ws = wb.worksheets[sheet]
    content = [
        [cell.value for j, cell in enumerate(row, start=1) if min_col <= j <= max_col]
        for i, row in enumerate(ws.iter_rows(), start=1)
        if min_row <= i <= max_row
    ]
    wb.close()
    return content


def get_authors(login: str) -> List[str]:
    root = STUDENTS_WORKS / login
    try:

        file_content = (root / "www/S105/auteurs.txt").read_text("utf8")
    except FileNotFoundError:
        print(f"WARNING: Pas de fichier auteurs.txt ({root})")
        file_content = ""
    return [
        author
        for line in file_content.split("\n")
        if (author := line.strip()) and not re.search(r"\d", author)
    ]


def merge_scores() -> None:
    login: str
    score: float
    manual_evaluation: Dict[str, float] = {}
    for login, score in xlsx2list(MANUAL_EVALUATIONS, max_col=2):
        if isinstance(login, str) and login[:2].isalpha() and login[2:].isnumeric():
            for author in get_authors(login):
                manual_evaluation[author] = float(score)
    automatic_evaluation: Dict[str, float] = {}
    for author, score in xlsx2list(AUTOMATIC_EVALUATIONS, max_col=2):
        try:
            automatic_evaluation[author] = float(score)
        except (TypeError, ValueError):
            pass
    final_evaluations: Dict[str, float] = {}
    for author in manual_evaluation:
        assert author in automatic_evaluation
        score = (
            MANUAL_EVALUATION_WEIGHT * manual_evaluation[author]
            + AUTOMATIC_EVALUATION_WEIGHT * automatic_evaluation[author]
        ) / (MANUAL_EVALUATION_WEIGHT + AUTOMATIC_EVALUATION_WEIGHT)
        final_evaluations[author] = round(score, ROUND_NDIGITS)
    list2xlsx(final_evaluations.items(), OUTPUT_FILE)
    print("\nSUCCESS ! File generated:", OUTPUT_FILE)


if __name__ == "__main__":
    merge_scores()
