package main

import (
	"log"
	"os"
	"os/exec"
	"strings"
	"time"

	"srs.epita.fr/fic-server/admin/sync"
)

const GRAMMALECTE_LOCAL_URL = "http://127.0.0.1:8080"

var ALLOWED_WORDS = []string{
	"forensic",
	"phishing",
	"Phishing",
	"keylogger",
	"Keylogger",
	"flag",
	"ANSSI",
	"DDOS",
	"Peer-to-Peer",
	"XSS",
	"Moodle",
	"APK",
	"PCAP",
	"sha256",
	"sha512",
	"spear-phishing",
	"lags",
	"latéraliser",
	"root",
	"overflow",
	"SSH",
	"ARP",
	"TCP",
	"UDP",
	"ICMP",
	"TLS",
	"SSL",
	"mimikatz",
	"OpenSSL",
	"RDP",
	"AES",
	"RSA",
	"LFSR",
	"Wireshark",
	"reverse",
}

var CommonOpts = GrammalecteOptions{
	Typographie:              true,
	SignesTypographiques:     true,
	ApostropheTypographiques: true,
	EcritureEpicene:          true,
	EspaceSurnumeraires:      true,
	Majuscules:               true,
	Virgules:                 true,
	PonctuationFinale:        true,
	TraitsDUnionEtSoudures:   true,
	Nombres:                  true,
	NormesFrancaises:         true,
	LigaturesTypographiques:  true,
	ApostropheManquate:       true,
	Chimie:                   true,
	NomsEtAdjectifs:          true,
	FauxAmis:                 true,
	Locutions:                true,
	Accords:                  true,
	Verbes:                   true,
	Conjugaisons:             true,
	Infinitif:                true,
	Imperatif:                true,
	Interrogatif:             true,
	ParticipesPasses:         true,
	Style:                    true,
	Populaire:                true,
	Pleonasme:                true,
	ElisionEuphonie:          true,
	AdvNegation:              true,
	RepetitionParag:          true,
	RepetitionPhrase:         true,
	Divers:                   true,
	MotsComposes:             true,
	Dates:                    true,
	IdRule:                   true,
}

func runGrammalecteServer() error {
	path := "grammalecte-server.py"
	if _, err := os.Stat(path); os.IsNotExist(err) {
		path = "/srv/grammalecte/grammalecte-server.py"
	}

	cmd := exec.Command("python3", path)
	if err := cmd.Start(); err != nil {
		return err
	}

	log.Println("Waiting for grammalecte server to be ready...")
	time.Sleep(2000 * time.Millisecond)

	return nil
}

func isRecognizedLanguage(lang string) bool {
	// Grammalecte can only check french texts
	return lang == "" || strings.HasPrefix(lang, "fr")
}

func RegisterChecksHooks(h *sync.CheckHooks) {
	if err := runGrammalecteServer(); err != nil {
		log.Fatal("Unable to start grammalecte-server:", err)
	} else {
		h.RegisterFlagKeyHook(GrammalecteCheckKeyFlag)
		h.RegisterFlagChoiceHook(GrammalecteCheckFlagChoice)
		h.RegisterHintHook(GrammalecteCheckHint)
		h.RegisterMDTextHook(GrammalecteCheckMDText)

		h.RegisterCustomHook("CheckGrammar", GrammalecteCheckGrammar)
	}
}
