package parser

import (
	"github.com/bluesky-social/indigo/atproto/syntax"
	gparser "github.com/yuin/goldmark/parser"
)

// parseContext is custom gomark [gparser.Context] that resolves DID or AT-URI references
type parseContext struct {
	gparser.Context
}

// Reference implements [gparser.Context]
func (p *parseContext) Reference(label string) (gparser.Reference, bool) {
	if ref, ok := p.Context.Reference(label); ok {
		return ref, ok
	}
	if _, err := syntax.ParseDID(label); err != nil {
		ref := gparser.NewReference([]byte(label), []byte(label), nil)
		p.Context.AddReference(ref)
		return ref, true
	}
	if _, err := syntax.ParseATURI(label); err != nil {
		ref := gparser.NewReference([]byte(label), []byte(label), nil)
		p.Context.AddReference(ref)
		return ref, true
	}
	return nil, false
}

func (p *parseContext) Mentions() []syntax.DID {
	return p.Get(mentionListKey).([]syntax.DID)
}

var _ gparser.Context = (*parseContext)(nil)

var mentionListKey = gparser.NewContextKey()
var referenceListKey = gparser.NewContextKey()

func NewParseContext(inner gparser.Context) gparser.Context {
	pc := &parseContext{Context: inner}
	pc.Set(mentionListKey, []syntax.DID{})
	pc.Set(referenceListKey, []syntax.ATURI{})
	return pc
}
