/*
 * Copyright (c) 2025-2026, Антон Аксенов
 * This file is part of iptvc project
 * MIT License: https://git.axenov.dev/IPTV/iptvc/src/branch/master/LICENSE
 */

package inifile

import (
	"axenov/iptv-checker/app/playlist"
	"axenov/iptv-checker/app/utils"
	"log"
	"os"
	"strings"

	"gopkg.in/ini.v1"
)

// IniFile описывает ini-файл c плейлистами
type IniFile struct {
	File  *ini.File
	Lists map[string]playlist.Playlist
}

// Init загружает данные из ini-файла
func Init(path string) (IniFile, error) {
	ini.DefaultHeader = false

	pathNormalized, err := utils.ExpandPath(path)
	if err != nil {
		return IniFile{}, err
	}

	_, err = os.Stat(pathNormalized)
	if err != nil {
		return IniFile{}, err
	}

	iniFile, err := ini.Load(pathNormalized)
	if err != nil {
		return IniFile{}, err
	}

	lists := make(map[string]playlist.Playlist)

	log.Println("Loading playlists from ini-file:", pathNormalized)
	for _, section := range iniFile.Sections() {
		if section.Name() == ini.DefaultSection {
			continue
		}

		name := getName(section)
		description := getValue("desc", section)
		source := getValue("src", section)
		url := getValue("pls", section)

		if url == "" {
			log.Printf("Warning: playlist [%s] has incorrect 'pls', skipping", section.Name())
			continue
		}

		lists[section.Name()] = playlist.Playlist{
			Code:        section.Name(),
			Name:        name,
			Description: description,
			Url:         section.KeysHash()["pls"],
			Source:      source,
		}
	}
	log.Printf("Loaded %d playlists\n", len(lists))

	return IniFile{
		File:  iniFile,
		Lists: lists,
	}, nil
}

// getValue возвращает значение по ключу в секции
func getValue(key string, section *ini.Section) string {
	if _, ok := section.KeysHash()[key]; !ok {
		return ""
	}

	value := strings.Trim(section.KeysHash()[key], "\n\t ")
	if value == "" {
		return ""
	}

	return value
}

// getName возвращает имя плейлиста по секции
func getName(section *ini.Section) string {
	name := getValue("name", section)
	if name == "" {
		return "Playlist #" + section.Name()
	}

	return name
}
