package main

import (
	"flag"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/goko/jingtian-tracker/config"
	"github.com/goko/jingtian-tracker/db"
	"github.com/goko/jingtian-tracker/pipeline"
	"github.com/goko/jingtian-tracker/watcher"
)

func main() {
	// Parse flags
	configPath := flag.String("config", "config.yaml", "Path to config file")
	flag.Parse()

	log.SetFlags(log.LstdFlags | log.Lshortfile)
	log.Println("JingTian Document Tracker starting...")

	// Load config
	cfg, err := config.Load(*configPath)
	if err != nil {
		log.Fatalf("Failed to load config: %v", err)
	}
	log.Printf("Config loaded: watching %s", cfg.Watch.Root)

	// Initialize database
	database, err := db.Open(cfg.Database.Path)
	if err != nil {
		log.Fatalf("Failed to open database: %v", err)
	}
	defer database.Close()
	log.Printf("Database initialized: %s", cfg.Database.Path)

	// Initialize watcher
	w, err := watcher.New(cfg)
	if err != nil {
		log.Fatalf("Failed to create watcher: %v", err)
	}

	// Initialize pipeline
	p, err := pipeline.New(cfg, database, w)
	if err != nil {
		log.Fatalf("Failed to create pipeline: %v", err)
	}
	defer p.Close()

	// Handle graceful shutdown
	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		<-sigChan
		log.Println("Shutdown signal received, stopping...")
		w.Stop()
	}()

	// Run pipeline
	if err := p.Run(); err != nil {
		log.Fatalf("Pipeline error: %v", err)
	}

	log.Println("JingTian Document Tracker stopped.")
}
