package upc

import (
	"fmt"

	lp "mgit.msbls.de/m/paliad/pkg/litigationplanner"
)

// SnapshotCourt is the embedded court row shape. Mirrors paliad.courts.
type SnapshotCourt struct {
	ID        string  `json:"id"`
	Code      string  `json:"code"`
	NameDE    string  `json:"name_de"`
	NameEN    string  `json:"name_en"`
	Country   string  `json:"country"`
	Regime    *string `json:"regime,omitempty"`
	CourtType string  `json:"court_type"`
	ParentID  *string `json:"parent_id,omitempty"`
	SortOrder int     `json:"sort_order"`
}

// SnapshotCourtRegistry serves CourtRegistry against the embedded
// court slice. UPC subset only (DE / EPA / DPMA courts are NOT in
// the snapshot — youpc.org has no need for them, and a request for
// a non-UPC court id falls through to default country/regime per the
// CountryRegime contract).
type SnapshotCourtRegistry struct {
	byID map[string]SnapshotCourt
}

// NewCourtRegistry parses the embedded courts.json and returns a
// ready-to-use registry.
func NewCourtRegistry() (*SnapshotCourtRegistry, error) {
	var courts []SnapshotCourt
	if err := readJSON("courts.json", &courts); err != nil {
		return nil, err
	}
	r := &SnapshotCourtRegistry{byID: make(map[string]SnapshotCourt, len(courts))}
	for _, c := range courts {
		r.byID[c.ID] = c
	}
	return r, nil
}

// CountryRegime resolves a court ID to its (country, regime) tuple.
// Empty courtID falls back to (defaultCountry, defaultRegime) per the
// interface contract. ErrUnknownCourt-equivalent (a plain error here)
// when courtID is non-empty but absent from the snapshot.
func (r *SnapshotCourtRegistry) CountryRegime(courtID, defaultCountry, defaultRegime string) (country, regime string, err error) {
	if courtID == "" {
		return defaultCountry, defaultRegime, nil
	}
	c, ok := r.byID[courtID]
	if !ok {
		return "", "", fmt.Errorf("upc snapshot: unknown court id %q", courtID)
	}
	reg := ""
	if c.Regime != nil {
		reg = *c.Regime
	}
	return c.Country, reg, nil
}

// Compile-time assertion that SnapshotCourtRegistry satisfies
// lp.CourtRegistry.
var _ lp.CourtRegistry = (*SnapshotCourtRegistry)(nil)
