package languages

import (
	"regexp"
	"strings"

	"github.com/zzet/gortex/internal/graph"
	"github.com/zzet/gortex/internal/parser"
)

// Objective-C / Objective-C++ is C-derived with `@` directives for
// class, protocol, and implementation declarations. Methods use a
// keyword-argument selector syntax: `- (ret)fooWith:(T)a andBar:(T)b`.
var (
	objcInterfaceRe = regexp.MustCompile(`(?m)^\s*@interface\s+(\w+)`)
	objcProtocolRe  = regexp.MustCompile(`(?m)^\s*@protocol\s+(\w+)`)
	objcImplRe      = regexp.MustCompile(`(?m)^\s*@implementation\s+(\w+)`)
	objcMethodRe    = regexp.MustCompile(`(?m)^\s*([-+])\s*\(\s*[^)]*\)\s*([A-Za-z_]\w*(?:\s*:\s*\([^)]*\)\s*\w+(?:\s+[A-Za-z_]\w*\s*:\s*\([^)]*\)\s*\w+)*)?)`)
	objcFuncRe      = regexp.MustCompile(`(?m)^\s*(?:static\s+|extern\s+|inline\s+)*[A-Za-z_][\w\s\*]*?\s+([A-Za-z_]\w*)\s*\([^)]*\)\s*\{`)
	objcImportQRe   = regexp.MustCompile(`(?m)^\s*#import\s+"([^"]+)"`)
	objcImportARe   = regexp.MustCompile(`(?m)^\s*#import\s+<([^>]+)>`)
	objcAtImportRe  = regexp.MustCompile(`(?m)^\s*@import\s+([\w.]+)`)
)

// ObjCExtractor extracts Objective-C / Objective-C++ source using regex.
type ObjCExtractor struct{}

func NewObjCExtractor() *ObjCExtractor { return &ObjCExtractor{} }

func (e *ObjCExtractor) Language() string     { return "objc" }
func (e *ObjCExtractor) Extensions() []string { return []string{".m", ".mm"} }

func (e *ObjCExtractor) Extract(filePath string, src []byte) (*parser.ExtractionResult, error) {
	lines := strings.Split(string(src), "\n")
	result := &parser.ExtractionResult{}

	fileNode := &graph.Node{
		ID: filePath, Kind: graph.KindFile, Name: filePath,
		FilePath: filePath, StartLine: 1, EndLine: len(lines),
		Language: "objc",
	}
	result.Nodes = append(result.Nodes, fileNode)

	seen := make(map[string]bool)
	add := func(name string, kind graph.NodeKind, start, end int) {
		if name == "" {
			return
		}
		id := filePath + "::" + name
		if seen[id] {
			return
		}
		seen[id] = true
		result.Nodes = append(result.Nodes, &graph.Node{
			ID: id, Kind: kind, Name: name,
			FilePath: filePath, StartLine: start, EndLine: end,
			Language: "objc",
		})
		result.Edges = append(result.Edges, &graph.Edge{
			From: fileNode.ID, To: id, Kind: graph.EdgeDefines,
			FilePath: filePath, Line: start,
		})
	}

	for _, m := range objcInterfaceRe.FindAllSubmatchIndex(src, -1) {
		name := string(src[m[2]:m[3]])
		line := lineAt(src, m[0])
		add(name, graph.KindType, line, findKeywordBlockEnd(lines, line, "@end"))
	}
	for _, m := range objcProtocolRe.FindAllSubmatchIndex(src, -1) {
		name := string(src[m[2]:m[3]])
		line := lineAt(src, m[0])
		add(name, graph.KindInterface, line, findKeywordBlockEnd(lines, line, "@end"))
	}
	for _, m := range objcImplRe.FindAllSubmatchIndex(src, -1) {
		name := string(src[m[2]:m[3]])
		line := lineAt(src, m[0])
		add(name, graph.KindType, line, findKeywordBlockEnd(lines, line, "@end"))
	}

	// Methods: build a selector name from the parts after the return type.
	for _, m := range objcMethodRe.FindAllSubmatchIndex(src, -1) {
		if m[4] < 0 {
			continue
		}
		sel := objcBuildSelector(string(src[m[4]:m[5]]))
		if sel == "" {
			continue
		}
		line := lineAt(src, m[0])
		add(sel, graph.KindMethod, line, findBlockEnd(lines, line))
	}

	// C-style function definitions.
	for _, m := range objcFuncRe.FindAllSubmatchIndex(src, -1) {
		name := string(src[m[2]:m[3]])
		if objcIsKeyword(name) {
			continue
		}
		line := lineAt(src, m[0])
		add(name, graph.KindFunction, line, findBlockEnd(lines, line))
	}

	emitImport := func(mod string, line int) {
		if mod == "" {
			return
		}
		result.Edges = append(result.Edges, &graph.Edge{
			From: fileNode.ID, To: "unresolved::import::" + mod,
			Kind: graph.EdgeImports, FilePath: filePath, Line: line,
		})
	}
	for _, m := range objcImportQRe.FindAllSubmatchIndex(src, -1) {
		emitImport(string(src[m[2]:m[3]]), lineAt(src, m[0]))
	}
	for _, m := range objcImportARe.FindAllSubmatchIndex(src, -1) {
		emitImport(string(src[m[2]:m[3]]), lineAt(src, m[0]))
	}
	for _, m := range objcAtImportRe.FindAllSubmatchIndex(src, -1) {
		emitImport(string(src[m[2]:m[3]]), lineAt(src, m[0]))
	}

	return result, nil
}

// objcBuildSelector takes the captured argument-slice of a method
// signature and returns the canonical selector with trailing colons
// for each keyword part, e.g. `fooWith:andBar:`.
func objcBuildSelector(raw string) string {
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return ""
	}
	// No colons — unary selector like `viewDidLoad`.
	if !strings.Contains(raw, ":") {
		// Take the first identifier.
		for i, r := range raw {
			isIdent := r == '_' ||
				(r >= 'a' && r <= 'z') ||
				(r >= 'A' && r <= 'Z') ||
				(r >= '0' && r <= '9' && i > 0)
			if !isIdent {
				return raw[:i]
			}
		}
		return raw
	}
	var parts []string
	depth := 0
	cur := strings.Builder{}
	for _, r := range raw {
		switch r {
		case '(':
			depth++
			continue
		case ')':
			if depth > 0 {
				depth--
			}
			continue
		}
		if depth > 0 {
			continue
		}
		if r == ' ' || r == '\t' || r == '\n' {
			if cur.Len() > 0 {
				parts = append(parts, cur.String())
				cur.Reset()
			}
			continue
		}
		cur.WriteRune(r)
	}
	if cur.Len() > 0 {
		parts = append(parts, cur.String())
	}
	var sel strings.Builder
	for _, p := range parts {
		idx := strings.Index(p, ":")
		if idx < 0 {
			continue
		}
		sel.WriteString(p[:idx])
		sel.WriteByte(':')
	}
	return sel.String()
}

func objcIsKeyword(s string) bool {
	switch s {
	case "if", "else", "while", "for", "do", "switch", "case", "default",
		"return", "break", "continue", "sizeof", "typedef", "struct",
		"enum", "union", "static", "extern", "inline", "const", "void":
		return true
	}
	return false
}

var _ parser.Extractor = (*ObjCExtractor)(nil)
