package parser

import (
	"encoding/json"
	"fmt"
	"os"
)

func (p *Parser) ParseRouteConfig(failed map[string][]string) error {
	err := p.mergeOutbound()
	if err != nil {
		return fmt.Errorf("merge outbound error: %s", err)
	}
	route, err := readAndMergeConfig[Routing](p.RemoteRoutePath, p.RoutePath)
	if err != nil {
		return fmt.Errorf("read route config error: %s", err)
	}
	needSave := false
	for region, fails := range failed {
		var tag string

		if t, ok := p.Outbound.Tags[region]; ok {
			tag = t
		} else {
			if t, ok := p.Outbound.Tags["other"]; !ok {
				continue
			} else {
				tag = t
			}
		}
		ds, is := p.getDomainAndIpRules(region, fails)
		if len(ds) == 0 &&
			len(is) == 0 {
			continue
		}
		first := true
		for i := range route.Rules {
			if tag != route.Rules[i].OutboundTag {
				continue
			}
			first = false
			if isRuleChanged(&route.Rules[i], ds, is) {
				needSave = true
				route.Rules[i].Domain = ds
				route.Rules[i].Ip = is
			}
		}
		if first {
			rule := Rule{
				Type:        "field",
				OutboundTag: tag,
				Domain:      ds,
				Ip:          is,
			}
			route.Rules = append([]Rule{rule}, route.Rules...)
			needSave = true
		}
	}
	if !needSave {
		return nil
	}
	f, err := os.OpenFile(p.RoutePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0744)
	if err != nil {
		return err
	}
	defer f.Close()
	e := json.NewEncoder(f)
	e.SetIndent("", "    ")
	err = e.Encode(&route)
	if err != nil {
		return fmt.Errorf("encode route file error: %s", err)
	}
	return nil
}
