1package parser
2
3import (
4 "fmt"
5 neturl "net/url"
6 "regexp"
7 "strings"
8 "time"
9
10 "github.com/bnema/dumber/internal/config"
11)
12
13// ParseInput parses user input and returns a ParseResult with URL and metadata.
14// Now uses the proven CLI parsing logic for consistent behavior.
15func (p *Parser) ParseInput(input string) (*ParseResult, error) {
16 startTime := time.Now()
17
18 if input == "" {
19 return &ParseResult{
20 Type: InputTypeFallbackSearch,
21 URL: "https://www.google.com/search?q=",
22 Query: input,
23 Confidence: 0.0,
24 ProcessingTime: time.Since(startTime),
25 }, nil
26 }
27
28 // Use the working CLI parsing logic
29 finalURL, err := p.parseInputUsingCLILogic(input)
30 if err != nil {
31 // If parsing fails, fall back to search
32 finalURL = fmt.Sprintf("https://www.google.com/search?q=%s", neturl.QueryEscape(input))
33 }
34
35 // Determine result type based on the URL
36 var resultType InputType = InputTypeFallbackSearch
37 confidence := 0.1
38
39 if strings.Contains(finalURL, "google.com/search") {
40 resultType = InputTypeFallbackSearch
41 confidence = 0.1
42 } else if strings.HasPrefix(finalURL, "http://") || strings.HasPrefix(finalURL, "https://") || strings.HasPrefix(finalURL, "dumb://") || strings.HasPrefix(finalURL, "file://") {
43 resultType = InputTypeDirectURL
44 confidence = 1.0
45 }
46
47 // Check if it was a shortcut
48 if idx := strings.Index(input, ":"); idx > 0 && idx < 10 && !strings.Contains(input, "://") {
49 shortcut := strings.TrimSpace(input[:idx])
50 if _, exists := p.config.SearchShortcuts[shortcut]; exists {
51 resultType = InputTypeSearchShortcut
52 confidence = 0.95
53 }
54 }
55
56 return &ParseResult{
57 Type: resultType,
58 URL: finalURL,
59 Query: input,
60 Confidence: confidence,
61 ProcessingTime: time.Since(startTime),
62 }, nil
63}
64
65// parseDirectURL handles direct URL inputs using CLI logic.
66func (p *Parser) parseDirectURL(cleanInput, originalInput string, startTime time.Time) (*ParseResult, error) {
67 // Use the working CLI parsing logic instead
68 finalURL, err := p.parseInputUsingCLILogic(cleanInput)
69 if err != nil {
70 return nil, err
71 }
72
73 return &ParseResult{
74 Type: InputTypeDirectURL,
75 URL: finalURL,
76 Query: originalInput,
77 Confidence: 1.0,
78 ProcessingTime: time.Since(startTime),
79 }, nil
80}
81
82// parseInputUsingCLILogic implements the working CLI parsing logic
83func (p *Parser) parseInputUsingCLILogic(input string) (string, error) {
84 input = strings.TrimSpace(input)
85
86 // 1. Check if it's a shortcut (format: "prefix:query")
87 if idx := strings.Index(input, ":"); idx > 0 && idx < 10 && !strings.Contains(input, "://") {
88 shortcut := strings.TrimSpace(input[:idx])
89 query := strings.TrimSpace(input[idx+1:])
90
91 if query != "" {
92 // First check configuration-based shortcuts
93 if shortcutCfg, exists := p.config.SearchShortcuts[shortcut]; exists {
94 return fmt.Sprintf(shortcutCfg.URL, neturl.QueryEscape(query)), nil
95 }
96
97 return "", fmt.Errorf("unknown shortcut '%s'", shortcut)
98 }
99 }
100
101 // 2. Already a full URL with protocol
102 if regexp.MustCompile(`^https?://`).MatchString(input) {
103 return input, nil
104 }
105
106 // 3. File protocol
107 if strings.HasPrefix(input, "file://") {
108 return input, nil
109 }
110
111 // 4. Dumb protocol for custom browser pages
112 if strings.HasPrefix(input, "dumb://") {
113 return input, nil
114 }
115
116 // 5. Localhost/development URLs
117 if regexp.MustCompile(`^(localhost|127\.0\.0\.1|0\.0\.0\.0|::1)(:\d+)?(/.*)?$`).MatchString(input) {
118 return "http://" + input, nil
119 }
120
121 // 6. Local network IPs
122 if regexp.MustCompile(`^(192\.168|10\.|172\.(1[6-9]|2[0-9]|3[01]))\.\d+\.\d+(:\d+)?(/.*)?$`).MatchString(input) {
123 return "http://" + input, nil
124 }
125
126 // 7. Domain with TLD (must have dot and valid TLD)
127 // More comprehensive TLD pattern for better URL detection
128 domainPattern := regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}(/.*)?$`)
129 if domainPattern.MatchString(input) {
130 // Additional check for common TLDs to reduce false positives
131 commonTLDs := regexp.MustCompile(`\.(com|org|net|edu|gov|io|co|uk|de|fr|jp|cn|in|br|au|ca|ru|nl|it|es|se|no|fi|dk|pl|ch|at|be|cz|gr|il|mx|nz|sg|kr|tw|hk|my|th|vn|id|ph|za|eg|ng|ke|dev|app|xyz|tech|site|online|store|blog|info|biz|name|pro)(/.*)?$`)
132 if commonTLDs.MatchString(input) {
133 return "https://" + input, nil
134 }
135
136 // If it has a dot but uncommon TLD, still try as URL
137 return "https://" + input, nil
138 }
139
140 // 8. Everything else is a search query
141 // This includes: single words, multi-word phrases, questions, special characters, etc.
142 // Single words without TLDs should be treated as search queries, not hostnames
143 return fmt.Sprintf("https://www.google.com/search?q=%s", neturl.QueryEscape(input)), nil
144}
145
146// parseSearchShortcut handles search shortcut inputs.
147func (p *Parser) parseSearchShortcut(cleanInput, originalInput string, startTime time.Time) (*ParseResult, error) {
148 validator := NewURLValidator()
149 isShortcut, shortcutKey, query := validator.IsSearchShortcut(cleanInput)
150
151 if !isShortcut {
152 return nil, fmt.Errorf("input is not a valid search shortcut")
153 }
154
155 // Look up the shortcut in configuration
156 shortcuts := p.config.SearchShortcuts
157 shortcutConfig, exists := shortcuts[shortcutKey]
158 if !exists {
159 // Unknown shortcut, treat as search query
160 return p.parseHistorySearch(cleanInput, originalInput, startTime)
161 }
162
163 // Build URL from shortcut template
164 finalURL, err := p.processShortcut(shortcutKey, query, shortcutConfig)
165 if err != nil {
166 return nil, fmt.Errorf("failed to process shortcut: %w", err)
167 }
168
169 return &ParseResult{
170 Type: InputTypeSearchShortcut,
171 URL: finalURL,
172 Query: originalInput,
173 Confidence: 0.95, // High confidence for known shortcuts
174 Shortcut: &DetectedShortcut{
175 Key: shortcutKey,
176 Query: query,
177 URL: finalURL,
178 Description: shortcutConfig.Description,
179 },
180 ProcessingTime: time.Since(startTime),
181 }, nil
182}
183
184// parseHistorySearch handles history search with fuzzy finding.
185func (p *Parser) parseHistorySearch(cleanInput, originalInput string, startTime time.Time) (*ParseResult, error) {
186 // Get history entries for fuzzy search
187 history, err := p.historyProvider.GetAllHistory()
188 if err != nil {
189 // If history search fails, fall back to web search
190 return p.parseFallbackSearch(cleanInput, originalInput, startTime)
191 }
192
193 // Perform fuzzy search
194 fuzzyMatcher := NewFuzzyMatcher(p.fuzzyConfig)
195 matches := fuzzyMatcher.SearchHistory(cleanInput, history)
196
197 // Check if we have good matches
198 if len(matches) > 0 && matches[0].Score >= p.fuzzyConfig.MinSimilarityThreshold {
199 // Use the best match
200 bestMatch := matches[0]
201
202 return &ParseResult{
203 Type: InputTypeHistorySearch,
204 URL: bestMatch.HistoryEntry.Url,
205 Query: originalInput,
206 Confidence: bestMatch.Score,
207 FuzzyMatches: matches,
208 ProcessingTime: time.Since(startTime),
209 }, nil
210 }
211
212 // No good history matches, fall back to search
213 fallbackResult, err := p.parseFallbackSearch(cleanInput, originalInput, startTime)
214 if err != nil {
215 return nil, err
216 }
217
218 // Include the fuzzy matches even though we're falling back
219 fallbackResult.FuzzyMatches = matches
220
221 return fallbackResult, nil
222}
223
224// parseFallbackSearch handles fallback web search.
225func (p *Parser) parseFallbackSearch(cleanInput, originalInput string, startTime time.Time) (*ParseResult, error) {
226 // Use default search shortcut (usually "g" for Google)
227 searchURL := p.buildSearchURL("", cleanInput)
228
229 return &ParseResult{
230 Type: InputTypeFallbackSearch,
231 URL: searchURL,
232 Query: originalInput,
233 Confidence: 0.1, // Low confidence for fallback
234 ProcessingTime: time.Since(startTime),
235 }, nil
236}
237
238// processShortcut processes a search shortcut and builds the final URL.
239func (p *Parser) processShortcut(shortcutKey, query string, shortcut config.SearchShortcut) (string, error) {
240 urlTemplate := shortcut.URL
241
242 // Replace placeholder with query
243 q := neturl.QueryEscape(query)
244 finalURL := strings.ReplaceAll(urlTemplate, "{query}", q)
245 finalURL = strings.ReplaceAll(finalURL, "%s", q)
246
247 // Validate the resulting URL
248 validator := NewURLValidator()
249 if !validator.IsValidURL(finalURL) && !strings.HasPrefix(finalURL, "http") {
250 return "", fmt.Errorf("invalid URL generated from shortcut '%s' template: %s", shortcutKey, finalURL)
251 }
252
253 return finalURL, nil
254}
255
256// buildSearchURL builds a search URL using the default search engine.
257func (p *Parser) buildSearchURL(searchEngine, query string) string {
258 q := neturl.QueryEscape(query)
259 // If no specific search engine, use Google as default
260 if searchEngine == "" {
261 defaultShortcut, exists := p.config.SearchShortcuts["g"]
262 if exists {
263 url := strings.ReplaceAll(defaultShortcut.URL, "{query}", q)
264 url = strings.ReplaceAll(url, "%s", q)
265 return url
266 }
267 // Fallback to Google if no "g" shortcut configured
268 return fmt.Sprintf("https://www.google.com/search?q=%s", q)
269 }
270
271 // Use specified search engine
272 shortcut, exists := p.config.SearchShortcuts[searchEngine]
273 if !exists {
274 return fmt.Sprintf("https://www.google.com/search?q=%s", q)
275 }
276
277 u := strings.ReplaceAll(shortcut.URL, "{query}", q)
278 u = strings.ReplaceAll(u, "%s", q)
279 return u
280}
281
282// FuzzySearchHistory performs fuzzy search on history and returns ranked matches.
283func (p *Parser) FuzzySearchHistory(query string, threshold float64) ([]FuzzyMatch, error) {
284 if query == "" {
285 return nil, nil
286 }
287
288 // Get all history entries
289 history, err := p.historyProvider.GetAllHistory()
290 if err != nil {
291 return nil, fmt.Errorf("failed to retrieve history: %w", err)
292 }
293
294 // Create fuzzy config with custom threshold if provided
295 fuzzyConfig := *p.fuzzyConfig
296 if threshold > 0 && threshold <= 1.0 {
297 fuzzyConfig.MinSimilarityThreshold = threshold
298 }
299
300 // Perform fuzzy search
301 fuzzyMatcher := NewFuzzyMatcher(&fuzzyConfig)
302 matches := fuzzyMatcher.SearchHistory(query, history)
303
304 // Apply additional ranking
305 matches = fuzzyMatcher.RankMatches(matches, query)
306
307 return matches, nil
308}
309
310// CalculateSimilarity calculates similarity between two strings.
311func (p *Parser) CalculateSimilarity(s1, s2 string) float64 {
312 fuzzyMatcher := NewFuzzyMatcher(p.fuzzyConfig)
313 return fuzzyMatcher.calculateSimilarity(s1, s2)
314}
315
316// RankMatches re-ranks fuzzy matches based on additional criteria.
317func (p *Parser) RankMatches(matches []FuzzyMatch, query string) []FuzzyMatch {
318 fuzzyMatcher := NewFuzzyMatcher(p.fuzzyConfig)
319 return fuzzyMatcher.RankMatches(matches, query)
320}
321
322// IsValidURL checks if the input represents a valid URL.
323func (p *Parser) IsValidURL(input string) bool {
324 validator := NewURLValidator()
325 return validator.IsValidURL(input)
326}
327
328// ProcessShortcut processes a shortcut and returns the resulting URL.
329func (p *Parser) ProcessShortcut(shortcut, query string, shortcuts map[string]config.SearchShortcut) (string, error) {
330 shortcutConfig, exists := shortcuts[shortcut]
331 if !exists {
332 return "", fmt.Errorf("shortcut '%s' not found", shortcut)
333 }
334
335 return p.processShortcut(shortcut, query, shortcutConfig)
336}
337
338// GetSupportedShortcuts returns a list of configured search shortcuts.
339func (p *Parser) GetSupportedShortcuts() map[string]config.SearchShortcut {
340 return p.config.SearchShortcuts
341}
342
343// UpdateFuzzyConfig updates the fuzzy matching configuration.
344func (p *Parser) UpdateFuzzyConfig(newConfig *FuzzyConfig) error {
345 if !newConfig.IsValid() {
346 return fmt.Errorf("invalid fuzzy configuration")
347 }
348
349 p.fuzzyConfig = newConfig
350 return nil
351}
352
353// GetFuzzyConfig returns the current fuzzy matching configuration.
354func (p *Parser) GetFuzzyConfig() *FuzzyConfig {
355 return p.fuzzyConfig
356}
357
358// PreviewParse provides a preview of what ParseInput would return without side effects.
359func (p *Parser) PreviewParse(input string) (*ParseResult, error) {
360 // This is essentially the same as ParseInput but could be extended
361 // to avoid any side effects if needed in the future
362 return p.ParseInput(input)
363}
364
365// SuggestCompletions provides URL/search completions based on input.
366func (p *Parser) SuggestCompletions(input string, limit int) ([]string, error) {
367 if input == "" || limit <= 0 {
368 return nil, nil
369 }
370
371 // Get fuzzy matches from history
372 matches, err := p.FuzzySearchHistory(input, 0.2) // Lower threshold for suggestions
373 if err != nil {
374 return nil, err
375 }
376
377 completions := make([]string, 0, limit)
378 seen := make(map[string]bool)
379
380 // Add URLs from fuzzy matches
381 for _, match := range matches {
382 if len(completions) >= limit {
383 break
384 }
385
386 url := match.HistoryEntry.Url
387 if !seen[url] {
388 completions = append(completions, url)
389 seen[url] = true
390 }
391 }
392
393 // Add search shortcuts if input looks like it might be a shortcut
394 if strings.Contains(input, ":") || len(input) <= 3 {
395 for shortcut, config := range p.config.SearchShortcuts {
396 if len(completions) >= limit {
397 break
398 }
399
400 if strings.HasPrefix(shortcut, strings.ToLower(input)) {
401 suggestion := fmt.Sprintf("%s: %s", shortcut, config.Description)
402 if !seen[suggestion] {
403 completions = append(completions, suggestion)
404 seen[suggestion] = true
405 }
406 }
407 }
408 }
409
410 return completions, nil
411}
412
413// ValidateConfig validates the parser configuration.
414func (p *Parser) ValidateConfig() error {
415 if p.config == nil {
416 return fmt.Errorf("parser config is nil")
417 }
418
419 if p.fuzzyConfig == nil {
420 return fmt.Errorf("fuzzy config is nil")
421 }
422
423 if !p.fuzzyConfig.IsValid() {
424 return fmt.Errorf("invalid fuzzy config")
425 }
426
427 if p.historyProvider == nil {
428 return fmt.Errorf("history provider is nil")
429 }
430
431 // Validate search shortcuts
432 if len(p.config.SearchShortcuts) == 0 {
433 return fmt.Errorf("no search shortcuts configured")
434 }
435
436 // Check for default search shortcut
437 if _, hasGoogle := p.config.SearchShortcuts["g"]; !hasGoogle {
438 // Warning: no default search configured
439 }
440
441 return nil
442}