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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# app.py
"""

Complete Keyword Research Pipeline

Integrates keyword discovery, analysis, and post-processing into one workflow

"""

import os
import sys
import argparse
from pathlib import Path
from dotenv import load_dotenv

# Load environment variables first
load_dotenv()

# Add current directory to path for imports
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

def check_setup():
    """Check if all requirements are met"""
    print("πŸ” Checking setup...")
    
    # Check API key
    api_key = os.getenv("SERPAPI_KEY")
    if not api_key:
        print("❌ SERPAPI_KEY not found in environment variables")
        print("Make sure your .env file contains: SERPAPI_KEY=your_key_here")
        return False
    
    print(f"βœ… API key found: {api_key[:10]}...")
    
    # Check required packages
    required_packages = [
        ('serpapi', 'google-search-results'),
        ('pandas', 'pandas'),
        ('tabulate', 'tabulate'),
        ('openpyxl', 'openpyxl')
    ]
    
    missing = []
    for import_name, pip_name in required_packages:
        try:
            __import__(import_name)
        except ImportError:
            missing.append(pip_name)
    
    if missing:
        print("❌ Missing packages:")
        for pkg in missing:
            print(f"   pip install {pkg}")
        return False
    
    print("βœ… All packages available")
    return True

def run_keyword_analysis(seed_keyword, use_volume_api=False):
    """Run the keyword analysis using the professional tool"""
    print("\nπŸ” Step 1: Running keyword analysis...")
    
    try:
        # Import and run the KeywordResearchTool
        import os
        import math
        import csv
        import re
        import logging
        from datetime import date
        from typing import List, Dict, Optional, Tuple, Any
        from dataclasses import dataclass
        from serpapi import GoogleSearch

        # Configure logging to be less verbose
        logging.basicConfig(level=logging.WARNING)
        
        @dataclass
        class KeywordMetrics:
            keyword: str
            monthly_searches: int
            competition_score: float
            opportunity_score: float
            total_results: int
            ads_count: int
            has_featured_snippet: bool
            has_people_also_ask: bool
            has_knowledge_graph: bool

        class CompetitionCalculator:
            WEIGHTS = {
                'total_results': 0.50,
                'ads': 0.25,
                'featured_snippet': 0.15,
                'people_also_ask': 0.07,
                'knowledge_graph': 0.03
            }
            
            @staticmethod
            def extract_total_results(search_info):
                if not search_info:
                    return 0
                
                total = (search_info.get("total_results") or 
                        search_info.get("total_results_raw") or 
                        search_info.get("total"))
                
                if isinstance(total, int):
                    return total
                
                if isinstance(total, str):
                    numbers_only = re.sub(r"[^\d]", "", total)
                    try:
                        return int(numbers_only) if numbers_only else 0
                    except ValueError:
                        return 0
                
                return 0
            
            def calculate_score(self, search_results):
                search_info = search_results.get("search_information", {})
                
                total_results = self.extract_total_results(search_info)
                normalized_results = min(math.log10(total_results + 1) / 7, 1.0)
                
                ads = search_results.get("ads_results", [])
                ads_count = len(ads) if ads else 0
                ads_score = min(ads_count / 3, 1.0)
                
                has_featured_snippet = bool(
                    search_results.get("featured_snippet") or 
                    search_results.get("answer_box")
                )
                
                has_people_also_ask = bool(
                    search_results.get("related_questions") or 
                    search_results.get("people_also_ask")
                )
                
                has_knowledge_graph = bool(search_results.get("knowledge_graph"))
                
                competition_score = (
                    self.WEIGHTS['total_results'] * normalized_results +
                    self.WEIGHTS['ads'] * ads_score +
                    self.WEIGHTS['featured_snippet'] * has_featured_snippet +
                    self.WEIGHTS['people_also_ask'] * has_people_also_ask +
                    self.WEIGHTS['knowledge_graph'] * has_knowledge_graph
                )
                
                competition_score = max(0.0, min(1.0, competition_score))
                
                breakdown = {
                    "total_results": total_results,
                    "ads_count": ads_count,
                    "has_featured_snippet": has_featured_snippet,
                    "has_people_also_ask": has_people_also_ask,
                    "has_knowledge_graph": has_knowledge_graph
                }
                
                return competition_score, breakdown

        # Main analysis functions
        def find_related_keywords(seed_keyword, max_results=120):
            print(f"Finding related keywords for: '{seed_keyword}'...")
            
            params = {
                "engine": "google",
                "q": seed_keyword,
                "api_key": os.getenv("SERPAPI_KEY"),
                "hl": "en",
                "gl": "us"
            }
            
            try:
                search = GoogleSearch(params)
                results = search.get_dict()
            except Exception as e:
                print(f"Error getting related keywords: {e}")
                return []
            
            keyword_candidates = set()
            
            # Get related searches
            related_searches = results.get("related_searches", [])
            for item in related_searches:
                query = item.get("query") or item.get("suggestion")
                if query and len(query.strip()) > 0:
                    keyword_candidates.add(query.strip())
            
            # Get people also ask
            related_questions = results.get("related_questions", [])
            for item in related_questions:
                question = item.get("question") or item.get("query")
                if question and len(question.strip()) > 0:
                    keyword_candidates.add(question.strip())
            
            # Get organic titles
            organic_results = results.get("organic_results", [])
            for result in organic_results[:10]:
                title = result.get("title", "")
                if title and len(title.strip()) > 0:
                    keyword_candidates.add(title.strip())
            
            final_keywords = list(keyword_candidates)[:max_results]
            print(f"Found {len(final_keywords)} keyword candidates")
            
            return final_keywords

        def analyze_keywords(keywords, use_volume_api=False):
            print(f"Analyzing {len(keywords)} keywords...")
            
            calculator = CompetitionCalculator()
            analyzed_keywords = []
            
            for i, keyword in enumerate(keywords, 1):
                if i % 10 == 0:
                    print(f"Progress: {i}/{len(keywords)} keywords processed")
                
                # Search for keyword
                params = {
                    "engine": "google",
                    "q": keyword,
                    "api_key": os.getenv("SERPAPI_KEY"),
                    "hl": "en",
                    "gl": "us",
                    "num": 10
                }
                
                try:
                    search = GoogleSearch(params)
                    search_results = search.get_dict()
                except Exception as e:
                    print(f"Error analyzing '{keyword}': {e}")
                    continue
                
                # Calculate competition
                competition_score, breakdown = calculator.calculate_score(search_results)
                
                # Estimate volume
                word_count = len(keyword.split())
                search_volume = max(10, 10000 // (word_count + 1))
                
                # Calculate opportunity score
                volume_score = math.log10(search_volume + 1)
                opportunity_score = volume_score / (competition_score + 0.01)
                
                metrics = KeywordMetrics(
                    keyword=keyword,
                    monthly_searches=search_volume,
                    competition_score=round(competition_score, 4),
                    opportunity_score=round(opportunity_score, 2),
                    total_results=breakdown["total_results"],
                    ads_count=breakdown["ads_count"],
                    has_featured_snippet=breakdown["has_featured_snippet"],
                    has_people_also_ask=breakdown["has_people_also_ask"],
                    has_knowledge_graph=breakdown["has_knowledge_graph"]
                )
                
                analyzed_keywords.append(metrics)
            
            # Sort by opportunity score
            analyzed_keywords.sort(key=lambda x: x.opportunity_score, reverse=True)
            
            print(f"Analysis complete! {len(analyzed_keywords)} keywords analyzed")
            return analyzed_keywords

        def save_to_csv(keyword_metrics, seed_keyword, top_count=50):
            if not keyword_metrics:
                print("No data to save!")
                return None
            
            # Create filename
            today = date.today()
            safe_seed = re.sub(r"[^\w\s-]", "", seed_keyword).strip().replace(" ", "_")[:30]
            filename = f"keywords_{safe_seed}_{today}.csv"
            
            try:
                with open(filename, "w", newline='', encoding='utf-8') as file:
                    writer = csv.writer(file)
                    
                    # Write header
                    headers = [
                        "Keyword", "Monthly Searches", "Competition Score", 
                        "Opportunity Score", "Total Results", "Ads Count",
                        "Featured Snippet", "People Also Ask", "Knowledge Graph"
                    ]
                    writer.writerow(headers)
                    
                    # Write data
                    for metrics in keyword_metrics[:top_count]:
                        row = [
                            metrics.keyword,
                            metrics.monthly_searches,
                            metrics.competition_score,
                            metrics.opportunity_score,
                            metrics.total_results,
                            metrics.ads_count,
                            "Yes" if metrics.has_featured_snippet else "No",
                            "Yes" if metrics.has_people_also_ask else "No",
                            "Yes" if metrics.has_knowledge_graph else "No"
                        ]
                        writer.writerow(row)
                
                saved_count = min(top_count, len(keyword_metrics))
                print(f"βœ… Saved {saved_count} keywords to {filename}")
                return filename
                
            except Exception as e:
                print(f"Error saving CSV: {e}")
                return None

        def display_top_results(keyword_metrics, top_count=5):
            if not keyword_metrics:
                print("No results to display!")
                return
            
            print(f"\nπŸ† Top {min(top_count, len(keyword_metrics))} Keywords:")
            print("-" * 80)
            
            for i, metrics in enumerate(keyword_metrics[:top_count], 1):
                print(f"{i}. {metrics.keyword}")
                print(f"   Score: {metrics.opportunity_score} | Volume: {metrics.monthly_searches:,} | Competition: {metrics.competition_score}")
                print()

        # Run the analysis
        related_keywords = find_related_keywords(seed_keyword)
        if not related_keywords:
            print("❌ No keyword candidates found")
            return None
        
        analyzed_keywords = analyze_keywords(related_keywords, use_volume_api)
        if not analyzed_keywords:
            print("❌ No keywords analyzed successfully")
            return None
        
        filename = save_to_csv(analyzed_keywords, seed_keyword)
        display_top_results(analyzed_keywords)
        
        return filename
        
    except Exception as e:
        print(f"❌ Error in keyword analysis: {e}")
        return None

def run_postprocessing(csv_filename, seed_keyword):
    """Run post-processing on the CSV file"""
    print("\n🧹 Step 2: Running post-processing...")
    
    try:
        import pandas as pd
        import re
        import json
        from datetime import date, datetime
        
        # Try to import optional packages
        try:
            from tabulate import tabulate
            HAS_TABULATE = True
        except ImportError:
            HAS_TABULATE = False
        
        try:
            import openpyxl
            HAS_EXCEL = True
        except ImportError:
            HAS_EXCEL = False

        # Configuration
        BRAND_KEYWORDS = {
            "linkedin", "indeed", "glassdoor", "ucla", "asu", "berkeley", 
            "hennge", "ciee", "google", "facebook", "microsoft", "amazon"
        }

        def is_brand_query(keyword):
            if not keyword:
                return False
            keyword_lower = keyword.lower()
            for brand in BRAND_KEYWORDS:
                if brand in keyword_lower:
                    return True
            if re.search(r"\.(com|edu|org|net|gov|io)\b", keyword_lower):
                return True
            return False

        def classify_intent(keyword):
            if not keyword:
                return "informational"
            
            k = keyword.lower()
            if any(signal in k for signal in ["how to", "what is", "why", "guide", "tutorial"]):
                return "informational"
            if any(signal in k for signal in ["buy", "price", "cost", "apply", "register"]):
                return "transactional"
            if any(signal in k for signal in ["best", "top", "compare", "vs", "reviews"]):
                return "commercial"
            if is_brand_query(keyword):
                return "navigational"
            return "informational"

        def classify_tail(keyword):
            if not keyword:
                return "short-tail"
            word_count = len(str(keyword).split())
            if word_count >= 4:
                return "long-tail"
            elif word_count == 3:
                return "mid-tail"
            else:
                return "short-tail"

        # Load and process the CSV
        print(f"Loading {csv_filename}...")
        df = pd.read_csv(csv_filename)
        print(f"Loaded {len(df)} keywords")
        
        # Clean and enhance the data
        print("Processing data...")
        
        # Standardize column names
        column_mapping = {
            'Keyword': 'Keyword',
            'Monthly Searches': 'Monthly Searches', 
            'Competition Score': 'Competition',
            'Opportunity Score': 'Opportunity Score',
            'Total Results': 'Google Results',
            'Ads Count': 'Ads Shown',
            'Featured Snippet': 'Featured Snippet?',
            'People Also Ask': 'PAA Available?',
            'Knowledge Graph': 'Knowledge Graph?'
        }
        
        # Rename columns that exist
        for old_name, new_name in column_mapping.items():
            if old_name in df.columns:
                df = df.rename(columns={old_name: new_name})
        
        # Remove duplicates and sort
        df = df.drop_duplicates(subset=['Keyword'], keep='first')
        df = df.sort_values('Opportunity Score', ascending=False)
        
        # Add enhancement columns
        df['Intent'] = df['Keyword'].apply(classify_intent)
        df['Tail'] = df['Keyword'].apply(classify_tail)
        df['Is Brand/Navigational'] = df['Keyword'].apply(lambda x: "Yes" if is_brand_query(x) else "No")
        
        # Reorder columns
        column_order = [
            'Keyword', 'Intent', 'Tail', 'Is Brand/Navigational',
            'Monthly Searches', 'Competition', 'Opportunity Score',
            'Google Results', 'Ads Shown', 'Featured Snippet?',
            'PAA Available?', 'Knowledge Graph?'
        ]
        
        available_columns = [col for col in column_order if col in df.columns]
        df = df[available_columns]
        
        # Create output directory
        os.makedirs("results", exist_ok=True)
        
        # Generate filenames
        today = date.today().isoformat()
        safe_seed = re.sub(r"[^\w\s-]", "", seed_keyword).strip().replace(" ", "_")[:30]
        base_name = f"keywords_{safe_seed}_{today}"
        
        csv_path = f"results/{base_name}.csv"
        excel_path = f"results/{base_name}.xlsx"
        meta_path = f"results/{base_name}.meta.json"
        
        # Save enhanced CSV
        df.to_csv(csv_path, index=False)
        print(f"πŸ’Ύ Saved enhanced CSV: {csv_path}")
        
        # Save Excel if available
        if HAS_EXCEL:
            with pd.ExcelWriter(excel_path, engine="openpyxl") as writer:
                df.head(50).to_excel(writer, sheet_name="Top_50", index=False)
                df.to_excel(writer, sheet_name="All_Keywords", index=False)
            print(f"πŸ“Š Saved Excel: {excel_path}")
        
        # Save metadata
        metadata = {
            "seed_keyword": seed_keyword,
            "generated_at": datetime.utcnow().isoformat() + "Z",
            "total_keywords": len(df),
            "data_source": "SerpApi with heuristic search volumes",
            "methodology": "Opportunity Score = log10(volume+1) / (competition + 0.01)"
        }
        
        with open(meta_path, "w", encoding="utf-8") as f:
            json.dump(metadata, f, indent=2)
        
        print(f"πŸ“‹ Saved metadata: {meta_path}")
        
        # Display results
        print(f"\nπŸ† Top 10 Enhanced Results:")
        
        preview_df = df.head(10)
        if HAS_TABULATE:
            display_columns = ['Keyword', 'Intent', 'Tail', 'Monthly Searches', 'Competition', 'Opportunity Score']
            display_data = preview_df[display_columns]
            print(tabulate(display_data, headers="keys", tablefmt="github", showindex=False))
        else:
            for i, row in preview_df.iterrows():
                print(f"{i+1}. {row['Keyword']} | Score: {row['Opportunity Score']} | Intent: {row['Intent']} | Tail: {row['Tail']}")
        
        # Summary stats
        print(f"\nπŸ“ˆ Summary:")
        print(f"β€’ Total keywords: {len(df)}")
        print(f"β€’ Long-tail keywords: {len(df[df['Tail'] == 'long-tail'])}")
        print(f"β€’ Non-brand keywords: {len(df[df['Is Brand/Navigational'] == 'No'])}")
        print(f"β€’ High opportunity (score > 50): {len(df[df['Opportunity Score'] > 50])}")
        
        return csv_path, excel_path, meta_path
        
    except Exception as e:
        print(f"❌ Error in post-processing: {e}")
        return None, None, None

def run_complete_pipeline(seed_keyword, use_volume_api=False):
    """Run the complete pipeline"""
    print("πŸš€ Starting Complete Keyword Research Pipeline")
    print("=" * 60)
    print(f"Seed Keyword: '{seed_keyword}'")
    print("=" * 60)
    
    # Step 1: Run keyword analysis
    csv_filename = run_keyword_analysis(seed_keyword, use_volume_api)
    
    if not csv_filename:
        print("❌ Pipeline failed at Step 1")
        return False
    
    # Step 2: Run post-processing
    csv_path, excel_path, meta_path = run_postprocessing(csv_filename, seed_keyword)
    
    if not csv_path:
        print("❌ Pipeline failed at Step 2")
        return False
    
    # Final summary
    print("\n🎯 PIPELINE COMPLETE! 🎯")
    print("=" * 60)
    print(f"πŸ“ Original CSV: {csv_filename}")
    print(f"πŸ“ Enhanced CSV: {csv_path}")
    if excel_path:
        print(f"πŸ“ Excel file: {excel_path}")
    if meta_path:
        print(f"πŸ“ Metadata: {meta_path}")
    print("=" * 60)
    
    return True

def main():
    """Main function with command line support"""
    parser = argparse.ArgumentParser(description="Complete Keyword Research Pipeline")
    parser.add_argument("seed_keyword", nargs="?", default="global internship", 
                       help="Seed keyword (default: 'global internship')")
    parser.add_argument("--use-volume-api", action="store_true",
                       help="Use real volume API (requires implementation)")
    parser.add_argument("--check-only", action="store_true",
                       help="Only check setup, don't run pipeline")
    
    args = parser.parse_args()
    
    # Check setup
    if not check_setup():
        return 1
    
    if args.check_only:
        print("βœ… Setup check complete!")
        return 0
    
    # Run pipeline
    success = run_complete_pipeline(args.seed_keyword, args.use_volume_api)
    return 0 if success else 1

if __name__ == "__main__":
    try:
        exit_code = main()
        sys.exit(exit_code)
    except KeyboardInterrupt:
        print("\n⚠️ Pipeline interrupted by user")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ Unexpected error: {e}")
        sys.exit(1)