import logging
import re
from datetime import datetime
from flask import Flask, render_template, request, redirect, url_for
from typing import Dict, Tuple

# Import du checker local (corrigé ci-dessous)
# On importe toujours la version qui retourne un dictionnaire de score
from dns_checker import check_all_dns_security, calculate_total_score

# --- Config & Logging ---
app = Flask(__name__)
app.config["DEBUG"] = False  # en prod, False ; en dev, tu peux mettre True

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("dnsentinel")

# Validation de domaine (simplifiée mais fiable)
DOMAIN_REGEX = re.compile(r"^(?=.{1,253}$)(?!-)(?:[A-Za-z0-9-]{1,63}\.)+[A-Za-z]{2,63}$")

def is_valid_domain(domain: str) -> bool:
    if not domain:
        return False
    d = domain.strip().lower()
    return bool(DOMAIN_REGEX.match(d))

# --- Routes ---
@app.route("/", methods=["GET"])
def index():
    current_year = datetime.now().year
    return render_template("index.html", current_year=current_year)

@app.route("/search", methods=["POST"])
def search():
    current_year = datetime.now().year
    try:
        domain = request.form.get("domain", "").strip()
        if not domain or not is_valid_domain(domain):
            # on redirige vers index avec message d'erreur simple (tu peux afficher error dans index.html si tu veux)
            return render_template("index.html", current_year=current_year, error="Domaine invalide. Exemple : example.com"), 400

        # Appel au checker (peut renvoyer FATAL_ERROR dans la structure)
        results = check_all_dns_security(domain)
        # Si le checker retourne une erreur fatale (outil manquant), on l'affiche proprement
        if "FATAL_ERROR" in results:
            fatal = results["FATAL_ERROR"]
            logger.error("FATAL ERROR from dns_checker: %s", fatal.get("detail"))
            return render_template("report.html",
                                   domain=domain,
                                   results={},
                                   score=0,
                                   max_score=100,
                                   current_year=current_year,
                                   error=fatal.get("detail")), 500

        # --- CORRECTION DE L'ERREUR ICI ---
        score_data = calculate_total_score(results)
        total_score = score_data['score']
        max_score = score_data['max_score']
        score_color = score_data['color']
        # -----------------------------------

        return render_template("report.html",
                               domain=domain,
                               results=results,
                               score=total_score,
                               max_score=max_score,
                               score_color=score_color,  # Passons la couleur au template
                               current_year=current_year)
    except Exception as exc:
        logger.exception("Erreur critique lors de l'analyse DNS : %s", exc)
        return render_template("report.html",
                               domain=request.form.get("domain", "N/A"),
                               results={},
                               score=0,
                               max_score=100,
                               score_color="red", # Valeur par défaut en cas d'erreur
                               current_year=current_year,
                               error=f"Erreur critique lors de l'analyse DNS : {exc}"), 500

@app.route("/recheck_dkim", methods=["POST"])
def recheck_dkim():
    current_year = datetime.now().year
    try:
        domain = request.form.get("domain", "").strip()
        selector = request.form.get("new_dkim_selector", "").strip()

        if not domain or not is_valid_domain(domain):
            return render_template("index.html", current_year=current_year, error="Domaine invalide."), 400
        if not selector:
            return render_template("report.html",
                                   domain=domain,
                                   results={},
                                   score=0,
                                   max_score=100,
                                   current_year=current_year,
                                   error="Sélecteur DKIM manquant."), 400

        results = check_all_dns_security(domain, dkim_selector=selector)
        if "FATAL_ERROR" in results:
            fatal = results["FATAL_ERROR"]
            logger.error("FATAL ERROR from dns_checker: %s", fatal.get("detail"))
            return render_template("report.html",
                                   domain=domain,
                                   results={},
                                   score=0,
                                   max_score=100,
                                   current_year=current_year,
                                   error=fatal.get("detail")), 500

        # --- CORRECTION DE L'ERREUR ICI ---
        score_data = calculate_total_score(results)
        total_score = score_data['score']
        max_score = score_data['max_score']
        score_color = score_data['color']
        # -----------------------------------

        return render_template("report.html",
                               domain=domain,
                               results=results,
                               score=total_score,
                               max_score=max_score,
                               score_color=score_color, # Passons la couleur au template
                               current_year=current_year)
    except Exception as exc:
        logger.exception("Erreur critique lors de la re-vérification DKIM : %s", exc)
        return render_template("report.html",
                               domain=request.form.get("domain", "N/A"),
                               results={},
                               score=0,
                               max_score=100,
                               score_color="red", # Valeur par défaut en cas d'erreur
                               current_year=current_year,
                               error=f"Erreur critique lors de la re-vérification DKIM : {exc}"), 500

# Health check
@app.route("/health", methods=["GET"])
def health():
    return "OK", 200

# Entrypoint dev
if __name__ == "__main__":
    # en dev uniquement
    app.run(host="0.0.0.0", port=5000, debug=True)
