# selinahbap.com x afair.live birlesik slot motoru: 50.000 slot, 8 bant; her GPT kendi slotunu atomik alir, cakisma olmaz.
"""python -B katki.py al --bant 1..8 --kimlik "<model>" [--sure 900]      bos slot al (sureli); ciktida slot no ve yapilacak is
python -B katki.py teslim --slot N --kimlik "<model>" --baslik "..." --metin "..." [--kanit "yol"]
python -B katki.py oner [--adet 8]        her bant icin siradaki bos slot ve ne eklenecegi
python -B katki.py derle                  public/katki.js uretir (sayfa bunu okur)
python -B katki.py durum
python -B katki.py selftest               yaris sinamasi: 8 ve 64 surec, cift slot 0

Kural: bir slot = bir dosya (veri/slot/s00001.json). Dosya O_EXCL ile yaratilir; ayni slotu iki surec alamaz.
Suresi dolan ayirma os.rename ile tek bir surece devredilir. Silme yok; eski ayirma .olu uzantisiyla kalir.
"""
from __future__ import annotations

import argparse
import json
import os
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path

BEN = Path(__file__).resolve()
KOK = Path(os.environ.get('KATKI_KOK') or BEN.parent)
SLOT = KOK / 'veri' / 'slot'
CIKTI = KOK / 'public' / 'katki.js'
TOPLAM, BANT_BOY = 50_000, 6_250
BANTLAR = [  # (ad, site, ne eklenir)
    ('Kapı', 'selinahbap', 'bir işin giriş kapısı: tek cümle iş tanımı ve bitti ölçütü'),
    ('Podyum', 'afair.live', 'bir defile sahnesinin tanımı: ışık, sıra, süre'),
    ('Koleksiyon', 'afair.live', 'bir parçanın kartı: kumaş, kesim, hikâye (kişisel veri yok)'),
    ('Stüdyo', 'afair.studio', 'bir tasarımcı alt alanının çalışma masası tarifi'),
    ('Yayın', 'afair.live', 'bir yayın akışının adımı: hazırlık, canlı, arşiv'),
    ('Ölçüm', 'selinahbap', 'bu bilgisayarda çalışan bir ölçüm aletinin yolu ve ölçtüğü şey'),
    ('Hareket', 'ortak', 'bir arayüz animasyonunun tarifi: tetik, süre, eğri'),
    ('Arayüz', 'ortak', 'bir arayüz parçasının tarifi: ne gösterir, hangi veriyle'),
]
SINIR = {'baslik': 80, 'metin': 600, 'kanit': 260, 'kimlik': 80}


class Ret(Exception):
    pass


def simdi() -> str:
    return datetime.now(timezone.utc).isoformat(timespec='seconds')


def yol(no: int) -> Path:
    return SLOT / f's{no:05d}.json'


def bant_araligi(b: int) -> range:
    if not 1 <= b <= 8:
        raise Ret('bant 1..8 olmalı')
    return range((b - 1) * BANT_BOY + 1, b * BANT_BOY + 1)


def oku(p: Path) -> dict | None:
    for _ in range(50):
        try:
            return json.loads(p.read_text('utf-8'))
        except FileNotFoundError:
            return None
        except (json.JSONDecodeError, PermissionError):
            time.sleep(0.01)  # yazan surec henuz bitirmedi
    return None


def yaz_yeni(p: Path, kayit: dict) -> bool:
    """O_EXCL: dosya varsa False. Kazanan tek surectir."""
    try:
        fd = os.open(p, os.O_CREAT | os.O_EXCL | os.O_WRONLY | getattr(os, 'O_BINARY', 0))
    except FileExistsError:
        return False
    with os.fdopen(fd, 'wb') as f:
        f.write(json.dumps(kayit, ensure_ascii=False).encode('utf-8'))
    return True


def suresi_doldu(k: dict | None) -> bool:
    return bool(k) and k.get('durum') == 'ayrildi' and time.time() > k.get('bitis', 0)


def al(bant: int, kimlik: str, sure: int) -> dict:
    SLOT.mkdir(parents=True, exist_ok=True)
    if '<' in kimlik or '>' in kimlik:
        raise Ret('kimlik şablonu aynen yapıştırılmış; kendi ürün ve model adını yaz')
    for no in bant_araligi(bant):
        p = yol(no)
        if p.exists():
            k = oku(p)
            if not suresi_doldu(k):
                continue
            try:  # suresi dolan ayirmayi tek surec devralir
                os.rename(p, p.with_suffix(f'.{int(time.time() * 1000)}.olu'))
            except OSError:
                continue
        kayit = {'slot': no, 'bant': bant, 'durum': 'ayrildi', 'kimlik': kimlik[:SINIR['kimlik']], 'utc': simdi(),
                 'bitis': time.time() + sure}
        if yaz_yeni(p, kayit):
            ad, site, ne = BANTLAR[bant - 1]
            return {'olay': 'ALINDI', 'slot': no, 'bant': f'{bant} {ad}', 'site': site, 'ne_ekle': ne, 'sure_sn': sure,
                    'teslim': f'python -B "{BEN}" teslim --slot {no} --kimlik "{kimlik}" --baslik "..." --metin "..."'}
    raise Ret(f'bant {bant} dolu')


TETIKLER = {  # tetik adi -> ne ister. Yeni tetigi GPT'ler ciktilarina gore ekler.
    'ozerk': 'GPT işi kendi seçer; kanıt isteğe bağlı',
    'ozel': 'iş sahibi işi adıyla verir; kanıt isteğe bağlı',
    'internet': 'iş yalnız internet sitesinden; kanıt https adresi + o sayfada geçen alıntı (motor sayfayı çekip doğrular)',
}


def sade(s: str) -> str:
    import html
    import re
    return re.sub(r'\s+', ' ', html.unescape(s)).strip().lower()


def web_dogrula(url: str, alinti: str) -> None:
    import urllib.request
    if not url.startswith('https://'):
        raise Ret('internet tetiğinde kanıt https adresi olmalı')
    if len(alinti.strip()) < 12:
        raise Ret('internet tetiğinde en az 12 karakterlik alıntı gerekir')
    try:
        istek = urllib.request.Request(url, headers={'User-Agent': 'katki-dogrulayici/1.0'})
        with urllib.request.urlopen(istek, timeout=25) as y:
            govde = y.read(3_000_000).decode('utf-8', 'ignore')
    except Exception as h:  # ag hatasi = kabul yok
        raise Ret(f'kaynak çekilemedi: {type(h).__name__}')
    if sade(alinti) not in sade(govde):
        raise Ret('alıntı kaynak sayfada geçmiyor')


def teslim(no: int, kimlik: str, baslik: str, metin: str, kanit: str, tetik: str = 'ozerk', alinti: str = '') -> dict:
    p = yol(no)
    k = oku(p)
    if not k:
        raise Ret('bu slot alınmamış; önce al')
    if k['durum'] != 'ayrildi' or k['kimlik'] != kimlik[:SINIR['kimlik']]:
        raise Ret('slot sende değil ya da zaten teslim edilmiş')
    if time.time() > k['bitis']:
        raise Ret('süre doldu; yeniden al')
    for ad, deger in (('baslik', baslik), ('metin', metin), ('kanit', kanit)):
        if len(deger) > SINIR[ad]:
            raise Ret(f'{ad} en çok {SINIR[ad]} karakter')
    if len(baslik.strip()) < 3 or len(metin.strip()) < 20:
        raise Ret('başlık en az 3, metin en az 20 karakter')
    if tetik not in TETIKLER:
        raise Ret(f'tetik şunlardan biri olmalı: {", ".join(TETIKLER)}')
    if len(alinti) > 200:
        raise Ret('alıntı en çok 200 karakter')
    if tetik == 'internet':
        web_dogrula(kanit, alinti)
    elif kanit and not kanit.startswith('https://') and not Path(kanit).exists():
        raise Ret('kanıt yolu diskte yok')
    k.update(durum='teslim', baslik=baslik.strip(), metin=metin.strip(), kanit=kanit, tetik=tetik, alinti=alinti.strip(),
             teslim_utc=simdi())
    gecici = p.with_suffix('.yaz')
    gecici.write_text(json.dumps(k, ensure_ascii=False), 'utf-8')
    os.replace(gecici, p)
    return {'olay': 'TESLIM', 'slot': no}


def hepsi() -> list[dict]:
    if not SLOT.exists():
        return []
    return [k for p in sorted(SLOT.glob('s*.json')) if (k := oku(p))]


def oner(adet: int) -> dict:
    dolu = {k['slot'] for k in hepsi() if not suresi_doldu(k)}
    s = []
    for b in range(1, 9):
        bos = [n for n in bant_araligi(b) if n not in dolu]
        ad, site, ne = BANTLAR[b - 1]
        s.append({'bant': f'{b} {ad}', 'site': site, 'ne_ekle': ne, 'bos_slot': len(bos),
                  'siradaki': bos[:adet], 'komut': f'python -B "{BEN}" al --bant {b} --kimlik "<ürün ve model>"'})
    return {'toplam': TOPLAM, 'dolu': len(dolu), 'bantlar': s}


def derle() -> dict:
    kayit = hepsi()
    teslim_ = [{'s': k['slot'], 'b': k['bant'], 'baslik': k['baslik'], 'metin': k['metin'], 'kimlik': k['kimlik'],
                'utc': k['teslim_utc'], 'tetik': k.get('tetik', 'ozerk'),
                # yerel yol yayina cikmaz; yalniz https kaynak ve alintisi
                'kaynak': k['kanit'] if k.get('kanit', '').startswith('https://') else '',
                'alinti': k.get('alinti', '') if k.get('kanit', '').startswith('https://') else ''}
               for k in kayit if k['durum'] == 'teslim']
    ayrildi = [k['slot'] for k in kayit if k['durum'] == 'ayrildi' and not suresi_doldu(k)]
    veri = {'uretim': simdi(), 'toplam': TOPLAM, 'bant_boy': BANT_BOY,
            'bantlar': [{'ad': a, 'site': s, 'ne': n} for a, s, n in BANTLAR], 'teslim': teslim_, 'ayrildi': ayrildi,
            'tetikler': [{'ad': a, 'ne': n, 'adet': sum(t['tetik'] == a for t in teslim_)} for a, n in TETIKLER.items()]}
    CIKTI.parent.mkdir(parents=True, exist_ok=True)
    if CIKTI.exists():  # veri ayniysa dosyaya dokunma: bos yayin olmasin
        try:
            eski = json.loads(CIKTI.read_text('utf-8').split('=', 1)[1].rstrip(';\n'))
        except (ValueError, IndexError):
            eski = None
        if eski and {**eski, 'uretim': None} == {**veri, 'uretim': None}:
            return {'olay': 'DEGISMEDI', 'teslim': len(teslim_), 'ayrildi': len(ayrildi), 'bayt': CIKTI.stat().st_size}
    gecici = CIKTI.with_suffix('.yaz')
    gecici.write_text('window.KATKI=' + json.dumps(veri, ensure_ascii=False) + ';\n', 'utf-8')
    os.replace(gecici, CIKTI)
    return {'olay': 'DERLENDI', 'teslim': len(teslim_), 'ayrildi': len(ayrildi), 'bayt': CIKTI.stat().st_size}


def selftest() -> dict:
    testler = []

    def bak(ad: str, kosul: bool) -> None:
        testler.append({'test': ad, 'gecti': bool(kosul)})
        if not kosul:
            raise AssertionError(ad)
    with tempfile.TemporaryDirectory() as g:
        ortam = {**os.environ, 'KATKI_KOK': g}

        def cagir(*a: str) -> subprocess.Popen:
            return subprocess.Popen([sys.executable, '-B', str(BEN), *a], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    text=True, encoding='utf-8', env=ortam)
        for n in (8, 64):
            t0 = time.perf_counter()
            ps = [cagir('al', '--bant', '2', '--kimlik', f'yarisci-{n}-{i}') for i in range(n)]
            cik = [json.loads(p.communicate()[0]) for p in ps]
            sure = time.perf_counter() - t0
            slotlar = [c['slot'] for c in cik if c.get('olay') == 'ALINDI']
            bak(f'{n} süreç: {n} ayrı slot, çift 0 ({sure:.2f} sn)', len(slotlar) == n == len(set(slotlar)))
        ilk = json.loads(cagir('al', '--bant', '1', '--kimlik', 'a', '--sure', '1').communicate()[0])
        bak('başkasının slotuna teslim reddedilir',
            cagir('teslim', '--slot', str(ilk['slot']), '--kimlik', 'b', '--baslik', 'xxx', '--metin', 'y' * 30).wait() == 1)
        bak('kendi slotuna teslim girer',
            cagir('teslim', '--slot', str(ilk['slot']), '--kimlik', 'a', '--baslik', 'Kapı bir', '--metin', 'deneme metni yirmi karakter').wait() == 0)
        iki = json.loads(cagir('al', '--bant', '1', '--kimlik', 'c', '--sure', '1').communicate()[0])
        time.sleep(1.2)
        uc = json.loads(cagir('al', '--bant', '1', '--kimlik', 'd').communicate()[0])
        bak('süresi dolan slot devredilir', uc['slot'] == iki['slot'])
        bak('şablon kimlik reddedilir', cagir('al', '--bant', '1', '--kimlik', '<ürün ve model>').wait() == 1)
        bak('sayfaya kötü metin yazılamaz (uzunluk)',
            cagir('teslim', '--slot', str(uc['slot']), '--kimlik', 'd', '--baslik', 'x' * 81, '--metin', 'y' * 30).wait() == 1)
        d = json.loads(cagir('derle').communicate()[0])
        bak('derle: 1 teslim, 73 ayrılmış', d['teslim'] == 1 and d['ayrildi'] == 73)
    return {'gecti': len(testler), 'toplam': len(testler), 'testler': testler}


def main() -> None:
    sys.stdout.reconfigure(encoding='utf-8')
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    alt = ap.add_subparsers(dest='is_', required=True)
    p = alt.add_parser('al')
    p.add_argument('--bant', type=int, required=True)
    p.add_argument('--kimlik', required=True)
    p.add_argument('--sure', type=int, default=900)
    p = alt.add_parser('teslim')
    p.add_argument('--slot', type=int, required=True)
    for ad in ('kimlik', 'baslik', 'metin'):
        p.add_argument('--' + ad, required=True)
    p.add_argument('--kanit', default='')
    p.add_argument('--tetik', default='ozerk', choices=list(TETIKLER))
    p.add_argument('--alinti', default='')
    alt.add_parser('oner').add_argument('--adet', type=int, default=3)
    alt.add_parser('derle')
    alt.add_parser('durum')
    alt.add_parser('selftest')
    a = ap.parse_args()
    try:
        if a.is_ == 'al':
            c = al(a.bant, a.kimlik, a.sure)
        elif a.is_ == 'teslim':
            c = teslim(a.slot, a.kimlik, a.baslik, a.metin, a.kanit, a.tetik, a.alinti)
        elif a.is_ == 'oner':
            c = oner(a.adet)
        elif a.is_ == 'derle':
            c = derle()
        elif a.is_ == 'durum':
            k = hepsi()
            c = {'toplam': TOPLAM, 'teslim': sum(x['durum'] == 'teslim' for x in k),
                 'ayrildi': sum(x['durum'] == 'ayrildi' and not suresi_doldu(x) for x in k)}
        else:
            c = selftest()
    except Ret as h:
        print(json.dumps({'olay': 'RET', 'neden': str(h)}, ensure_ascii=False))
        raise SystemExit(1)
    print(json.dumps(c, ensure_ascii=False, indent=1))


if __name__ == '__main__':
    main()
