package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"git.kingecg.top/kingecg/goffmpeg/pkg/ffmpeg"
)

func main() {
	inputURL := flag.String("i", "", "Input file or URL")
	outputURL := flag.String("o", "", "Output file or URL")
	codecName := flag.String("c", "", "Codec name (e.g., libx264, aac)")
	flag.Parse()

	if *inputURL == "" || *outputURL == "" {
		flag.Usage()
		os.Exit(1)
	}

	// Open input
	ic := ffmpeg.AllocFormatContext()
	defer ic.Free()

	if err := ic.OpenInput(*inputURL); err != nil {
		log.Fatalf("Failed to open input: %v", err)
	}
	defer ic.Close()

	if err := ic.FindStreamInfo(); err != nil {
		log.Fatalf("Failed to find stream info: %v", err)
	}

	ic.DumpFormat(0, *inputURL, false)

	// Find video stream
	videoStreams := ic.VideoStreams()
	if len(videoStreams) == 0 {
		log.Fatal("No video stream found")
	}

	// Open output context
	var ofc *ffmpeg.OutputFormatContext
	if *codecName != "" {
		codec, err := ffmpeg.FindEncoder(*codecName)
		if err != nil {
			log.Fatalf("Failed to find encoder: %v", err)
		}

		of := ffmpeg.GuessFormat("", *outputURL)
		if of == nil {
			log.Fatalf("Failed to guess format")
		}

		ofc, err = ffmpeg.AllocOutputContext(*outputURL, of)
		if err != nil {
			log.Fatalf("Failed to allocate output context: %v", err)
		}

		stream, err := ofc.AddStream(codec)
		if err != nil {
			log.Fatalf("Failed to add stream: %v", err)
		}

		vs := videoStreams[0]
		cp := vs.CodecParameters()
		stream.SetCodecParameters(cp)
	} else {
		var err error
		ofc, err = ffmpeg.AllocOutputContext(*outputURL, nil)
		if err != nil {
			log.Fatalf("Failed to allocate output context: %v", err)
		}
	}

	defer ofc.Free()

	fmt.Println("Transcoding started...")
	fmt.Printf("Input: %s\n", *inputURL)
	fmt.Printf("Output: %s\n", *outputURL)
}
