#!/usr/bin/env python3
# AIX CLI — içerik dosyalarını AI-izi açısından denetler. CI için exit kodu döner.
# Kurulum: chmod +x aix-cli.py  ·  Anahtar: export AIX_KEY=aix_...
# Kullanım: ./aix-cli.py dosya.md [dosya2.txt ...] [--max 37] [--lang tr]
import sys, os, json, urllib.request, urllib.error, glob

API = os.environ.get("AIX_API", "https://aix.xtro.ovh/api/v1") + "/analyze"
KEY = os.environ.get("AIX_KEY", "")

def analyze(text, lang):
    req = urllib.request.Request(API, method="POST",
        headers={"Content-Type": "application/json", "Authorization": "Bearer " + KEY},
        data=json.dumps({"text": text[:20000], "lang": lang}).encode())
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.loads(r.read().decode())

def main():
    args = sys.argv[1:]
    if not args or "-h" in args or "--help" in args:
        print("Kullanim: aix-cli.py dosya... [--max N] [--lang tr|en]"); return 0
    if not KEY:
        print("Hata: AIX_KEY tanimli degil (export AIX_KEY=aix_...)"); return 2
    max_score, lang, files = 37, "tr", []
    i = 0
    while i < len(args):
        if args[i] == "--max": max_score = int(args[i+1]); i += 2
        elif args[i] == "--lang": lang = args[i+1]; i += 2
        else: files += glob.glob(args[i]) or [args[i]]; i += 1
    worst = 0; fail = 0
    for f in files:
        try:
            with open(f, encoding="utf-8") as fh: text = fh.read()
        except OSError as e:
            print("!! " + f + ": okunamadi (" + str(e) + ")"); continue
        if len(text.strip()) < 20:
            print(".. " + f + ": cok kisa, atlandi"); continue
        try:
            d = analyze(text, lang)
        except urllib.error.HTTPError as e:
            print("!! " + f + ": API hatasi " + str(e.code)); fail += 1; continue
        except Exception as e:
            print("!! " + f + ": " + str(e)); fail += 1; continue
        sc = d.get("score", 0); n = d.get("counts", {}).get("findings", 0)
        mark = "OK" if sc < max_score else "XX"
        print(mark + " " + f + ": skor " + str(sc) + "/100 (" + str(n) + " iz)")
        worst = max(worst, sc)
        if sc >= max_score: fail += 1
    print("--- en yuksek skor: " + str(worst) + " / esik: " + str(max_score))
    return 1 if fail else 0

if __name__ == "__main__":
    sys.exit(main())