import sys
import subprocess
import os
import time
import importlib.util
from datetime import datetime

gerekli_kutuphaneler = ['watchdog', 'rich']
eksik_kutuphaneler = []

for lib in gerekli_kutuphaneler:
    if importlib.util.find_spec(lib) is None:
        eksik_kutuphaneler.append(lib)

if eksik_kutuphaneler:
    lib_isimleri = ", ".join(eksik_kutuphaneler)
    print(f"Bu betiği çalıştırabilmek için {lib_isimleri} kütüphanesinin/kütüphanelerinin yüklü olması gerekmektedir.")
    while True:
        secim = input("Şimdi yüklensin mi? (E/H): ").strip().lower()
        if secim == 'e':
            try:
                subprocess.check_call([sys.executable, "-m", "pip", "install"] + eksik_kutuphaneler)
                print("\nKütüphaneler başarıyla yüklendi. Program yeniden başlatılıyor...\n")
                time.sleep(1)
                os.execl(sys.executable, sys.executable, *sys.argv)
            except Exception as e:
                print(f"Yükleme sırasında hata oluştu: {e}")
                input("Çıkmak için Enter'a basın...")
                sys.exit()
            break
        elif secim == 'h':
            print("Kütüphaneler yüklenmediği için program sonlandırılıyor.")
            input("Çıkmak için Enter'a basın...")
            sys.exit()

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from rich.live import Live
from rich.table import Table
from rich.console import Console

TOP_N = 10

class DosyaTakip(FileSystemEventHandler):
    def __init__(self, izlenen_dizin, dosya_listesi):
        self.izlenen_dizin = izlenen_dizin
        self.dosya_listesi = dosya_listesi

    def _listeyi_guncelle(self, dosya_yolu):
        try:
            if os.path.isdir(dosya_yolu):
                return

            zaman_damgasi = os.path.getmtime(dosya_yolu)
            
            self.dosya_listesi[:] = [x for x in self.dosya_listesi if x['yol'] != dosya_yolu]
            
            self.dosya_listesi.append({
                'yol': dosya_yolu,
                'zaman': zaman_damgasi
            })
            
            self.dosya_listesi.sort(key=lambda x: x['zaman'], reverse=True)
            
            if len(self.dosya_listesi) > TOP_N:
                self.dosya_listesi[:] = self.dosya_listesi[:TOP_N]
                
        except (FileNotFoundError, PermissionError):
            pass

    def on_modified(self, event):
        self._listeyi_guncelle(event.src_path)

    def on_created(self, event):
        self._listeyi_guncelle(event.src_path)

    def on_moved(self, event):
        self._listeyi_guncelle(event.dest_path)

def baslangic_taramasi(dizin):
    dosyalar = []
    print(f"Lütfen bekleyin, '{dizin}' taranıyor...")
    
    for root, _, files in os.walk(dizin):
        for file in files:
            try:
                tam_yol = os.path.join(root, file)
                zaman = os.path.getmtime(tam_yol)
                dosyalar.append({'yol': tam_yol, 'zaman': zaman})
            except (OSError, PermissionError):
                continue
    
    dosyalar.sort(key=lambda x: x['zaman'], reverse=True)
    return dosyalar[:TOP_N]

def tablo_olustur(dosyalar, ana_dizin):
    table = Table(title=f"📁 İzlenen Dizin: {ana_dizin}", expand=True, border_style="blue")

    table.add_column("📂 Dosya Yolu (Göreceli)", style="cyan", no_wrap=True)
    table.add_column("🕒 Son Güncelleme", style="green", width=25)

    if not dosyalar:
        table.add_row("Henüz bir değişiklik algılanmadı...", "-")
    else:
        for dosya in dosyalar:
            try:
                gosterilecek_yol = os.path.relpath(dosya['yol'], ana_dizin)
            except ValueError:
                gosterilecek_yol = dosya['yol']

            zaman_str = datetime.fromtimestamp(dosya['zaman']).strftime('%Y-%m-%d %H:%M:%S')
            table.add_row(gosterilecek_yol, zaman_str)

    return table

def main():
    console = Console()

    while True:
        target_dir = input("İzlemek istediğiniz dizini girin: ").strip()
        target_dir = target_dir.replace('"', '').replace("'", "")
        
        if os.path.isdir(target_dir):
            break
        else:
            console.print(f"[bold red]Hata:[/bold red] '{target_dir}' geçerli bir dizin değil. Lütfen tekrar deneyin.")

    current_files = baslangic_taramasi(target_dir)

    event_handler = DosyaTakip(target_dir, current_files)
    observer = Observer()
    observer.schedule(event_handler, target_dir, recursive=True)
    observer.start()

    console.clear()
    console.print(f"[bold green]İzleme başladı... Çıkmak için Ctrl + C basın.[/bold green]")

    try:
        with Live(tablo_olustur(current_files, target_dir), refresh_per_second=4, screen=True) as live:
            while True:
                live.update(tablo_olustur(current_files, target_dir))
                time.sleep(0.1)
    except KeyboardInterrupt:
        observer.stop()
        console.print("\n[bold red]İzleme kullanıcı tarafından durduruldu.[/bold red]")
    
    observer.join()

if __name__ == "__main__":
    main()