File size: 14,148 Bytes
61d29fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Google Civic Information API Integration

The Google Civic Information API is the gold standard for:
- Address-to-representative mapping
- Elected officials contact information
- Election data and polling locations
- Voter information

API Docs: https://developers.google.com/civic-information
Free Tier: 25,000 requests/day
Cost: Free for non-commercial use

SETUP:
1. Get API key: https://console.cloud.google.com/
2. Enable "Google Civic Information API"
3. Add to .env: GOOGLE_CIVIC_API_KEY=your-key

USAGE:
    from discovery.google_civic_integration import GoogleCivicAPI
    
    api = GoogleCivicAPI()
    
    # Get representatives for an address
    reps = await api.get_representatives("1600 Pennsylvania Ave NW, Washington DC")
    
    # Get upcoming elections
    elections = await api.get_elections()
    
    # Get voter info
    voter_info = await api.get_voter_info("123 Main St, Tuscaloosa, AL")
"""
import asyncio
from typing import Dict, List, Optional
from datetime import datetime
from pathlib import Path
import httpx
from loguru import logger

try:
    from pyspark.sql import SparkSession
    from config.settings import settings
    SPARK_AVAILABLE = True
except ImportError:
    SPARK_AVAILABLE = False
    settings = None
    logger.warning("Running without Spark/settings - limited functionality")


class GoogleCivicAPI:
    """
    Integration with Google Civic Information API.
    
    Best for:
    - "Who represents this address?" queries
    - Finding all elected officials for a location
    - Election information
    - Polling locations
    """
    
    BASE_URL = "https://www.googleapis.com/civicinfo/v2"
    
    def __init__(self, api_key: Optional[str] = None):
        """
        Initialize Google Civic API client.
        
        Args:
            api_key: Google Civic Information API key
                    If not provided, will try to get from settings.google_civic_api_key
        """
        if api_key:
            self.api_key = api_key
        elif SPARK_AVAILABLE and hasattr(settings, 'google_civic_api_key'):
            self.api_key = settings.google_civic_api_key
        else:
            self.api_key = None
            logger.warning("⚠️  GOOGLE_CIVIC_API_KEY not found")
            logger.warning("   Get one at: https://console.cloud.google.com/")
            logger.warning("   Add to .env: GOOGLE_CIVIC_API_KEY=your-key")
        
        self.cache_dir = Path("data/cache/google_civic")
        self.cache_dir.mkdir(parents=True, exist_ok=True)
    
    async def get_representatives(
        self,
        address: str,
        levels: Optional[List[str]] = None,
        roles: Optional[List[str]] = None
    ) -> Dict:
        """
        Get elected officials for a given address.
        
        Args:
            address: Street address (e.g., "1600 Pennsylvania Ave NW, Washington DC")
            levels: Filter by government level: ['country', 'administrativeArea1' (state), 
                   'administrativeArea2' (county), 'locality' (city), 'subLocality1' (neighborhood)]
            roles: Filter by role: ['legislatorUpperBody', 'legislatorLowerBody', 
                  'deputyHeadOfGovernment', 'headOfGovernment', 'executiveCouncil', etc.]
        
        Returns:
            Dict with 'offices' and 'officials' keys
        """
        if not self.api_key:
            raise ValueError("Google Civic API key required. Set GOOGLE_CIVIC_API_KEY in .env")
        
        params = {
            "address": address,
            "key": self.api_key
        }
        
        if levels:
            params["levels"] = levels
        if roles:
            params["roles"] = roles
        
        logger.info(f"Fetching representatives for: {address}")
        
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                response = await client.get(
                    f"{self.BASE_URL}/representatives",
                    params=params
                )
                response.raise_for_status()
                data = response.json()
                
                # Extract and format data
                officials_data = {
                    "address": address,
                    "normalized_address": data.get("normalizedInput", {}).get("line1", address),
                    "officials": [],
                    "source": "google_civic_api",
                    "fetched_at": datetime.utcnow().isoformat()
                }
                
                # Parse offices and officials
                offices = data.get("offices", [])
                officials = data.get("officials", [])
                
                for office in offices:
                    office_name = office.get("name")
                    office_level = office.get("levels", ["unknown"])[0]
                    office_roles = office.get("roles", [])
                    
                    # Get official indices for this office
                    official_indices = office.get("officialIndices", [])
                    
                    for idx in official_indices:
                        if idx < len(officials):
                            official = officials[idx]
                            
                            officials_data["officials"].append({
                                "name": official.get("name"),
                                "office": office_name,
                                "level": office_level,
                                "roles": office_roles,
                                "party": official.get("party"),
                                "phones": official.get("phones", []),
                                "urls": official.get("urls", []),
                                "emails": official.get("emails", []),
                                "photo_url": official.get("photoUrl"),
                                "address": official.get("address", [{}])[0] if official.get("address") else {},
                                "channels": official.get("channels", [])  # Social media
                            })
                
                logger.info(f"✅ Found {len(officials_data['officials'])} officials for {address}")
                return officials_data
                
            except httpx.HTTPStatusError as e:
                logger.error(f"HTTP error: {e.response.status_code} - {e.response.text}")
                raise
            except Exception as e:
                logger.error(f"Error fetching representatives: {e}")
                raise
    
    async def get_elections(self) -> Dict:
        """
        Get information about upcoming elections.
        
        Returns:
            Dict with 'elections' list
        """
        if not self.api_key:
            raise ValueError("Google Civic API key required")
        
        logger.info("Fetching upcoming elections")
        
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                response = await client.get(
                    f"{self.BASE_URL}/elections",
                    params={"key": self.api_key}
                )
                response.raise_for_status()
                data = response.json()
                
                elections_data = {
                    "elections": data.get("elections", []),
                    "source": "google_civic_api",
                    "fetched_at": datetime.utcnow().isoformat()
                }
                
                logger.info(f"✅ Found {len(elections_data['elections'])} upcoming elections")
                return elections_data
                
            except Exception as e:
                logger.error(f"Error fetching elections: {e}")
                raise
    
    async def get_voter_info(
        self,
        address: str,
        election_id: Optional[str] = None
    ) -> Dict:
        """
        Get voter information for an address.
        
        Args:
            address: Voter's address
            election_id: Specific election ID (default: next election)
        
        Returns:
            Dict with polling location, ballot info, etc.
        """
        if not self.api_key:
            raise ValueError("Google Civic API key required")
        
        params = {
            "address": address,
            "key": self.api_key
        }
        
        if election_id:
            params["electionId"] = election_id
        
        logger.info(f"Fetching voter info for: {address}")
        
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                response = await client.get(
                    f"{self.BASE_URL}/voterinfo",
                    params=params
                )
                response.raise_for_status()
                data = response.json()
                
                voter_info = {
                    "address": address,
                    "normalized_address": data.get("normalizedInput", {}).get("line1", address),
                    "election": data.get("election"),
                    "polling_locations": data.get("pollingLocations", []),
                    "early_vote_sites": data.get("earlyVoteSites", []),
                    "contests": data.get("contests", []),
                    "state": data.get("state", []),
                    "source": "google_civic_api",
                    "fetched_at": datetime.utcnow().isoformat()
                }
                
                logger.info(f"✅ Found voter info for {address}")
                return voter_info
                
            except Exception as e:
                logger.error(f"Error fetching voter info: {e}")
                raise
    
    async def get_representatives_by_division(self, ocd_id: str) -> Dict:
        """
        Get representatives for an Open Civic Data division ID.
        
        Args:
            ocd_id: OCD ID (e.g., "ocd-division/country:us/state:al/county:tuscaloosa")
        
        Returns:
            Dict with officials for that division
        """
        if not self.api_key:
            raise ValueError("Google Civic API key required")
        
        logger.info(f"Fetching representatives for OCD ID: {ocd_id}")
        
        async with httpx.AsyncClient(timeout=30.0) as client:
            try:
                response = await client.get(
                    f"{self.BASE_URL}/representatives/{ocd_id}",
                    params={"key": self.api_key}
                )
                response.raise_for_status()
                return response.json()
                
            except Exception as e:
                logger.error(f"Error fetching division representatives: {e}")
                raise
    
    def save_to_json(self, data: Dict, filename: str):
        """Save data to JSON cache."""
        import json
        
        filepath = self.cache_dir / filename
        with open(filepath, 'w') as f:
            json.dump(data, f, indent=2)
        
        logger.info(f"💾 Saved to {filepath}")


# ============================================================================
# Example Usage
# ============================================================================

async def example_usage():
    """Example usage of Google Civic API."""
    
    # Initialize (will get key from settings or environment)
    api = GoogleCivicAPI()
    
    if not api.api_key:
        logger.error("❌ API key not found. Please set GOOGLE_CIVIC_API_KEY in .env")
        return
    
    # Example 1: Get representatives for Tuscaloosa City Hall
    logger.info("\n" + "="*80)
    logger.info("Example 1: Get representatives for Tuscaloosa, AL")
    logger.info("="*80)
    
    try:
        reps = await api.get_representatives("2201 University Blvd, Tuscaloosa, AL 35401")
        
        print(f"\n✅ Found {len(reps['officials'])} officials:")
        for official in reps['officials'][:10]:  # Show first 10
            print(f"\n   • {official['name']}")
            print(f"     Office: {official['office']}")
            print(f"     Level: {official['level']}")
            print(f"     Party: {official.get('party', 'N/A')}")
            if official.get('phones'):
                print(f"     Phone: {official['phones'][0]}")
            if official.get('urls'):
                print(f"     Website: {official['urls'][0]}")
        
        # Save to cache
        api.save_to_json(reps, "tuscaloosa_representatives.json")
        
    except Exception as e:
        logger.error(f"Error: {e}")
    
    # Example 2: Get upcoming elections
    logger.info("\n" + "="*80)
    logger.info("Example 2: Get upcoming elections")
    logger.info("="*80)
    
    try:
        elections = await api.get_elections()
        
        print(f"\n✅ Found {len(elections['elections'])} upcoming elections:")
        for election in elections['elections']:
            print(f"\n   • {election['name']}")
            print(f"     Date: {election['electionDay']}")
            print(f"     ID: {election['id']}")
        
        api.save_to_json(elections, "upcoming_elections.json")
        
    except Exception as e:
        logger.error(f"Error: {e}")
    
    # Example 3: Get voter info
    logger.info("\n" + "="*80)
    logger.info("Example 3: Get voter information")
    logger.info("="*80)
    
    try:
        voter_info = await api.get_voter_info("2201 University Blvd, Tuscaloosa, AL 35401")
        
        print(f"\n✅ Voter Information:")
        print(f"   Election: {voter_info['election']['name'] if voter_info.get('election') else 'None upcoming'}")
        if voter_info.get('polling_locations'):
            print(f"   Polling Locations: {len(voter_info['polling_locations'])}")
        if voter_info.get('contests'):
            print(f"   Ballot Contests: {len(voter_info['contests'])}")
        
        api.save_to_json(voter_info, "tuscaloosa_voter_info.json")
        
    except Exception as e:
        logger.error(f"Error: {e}")
    
    logger.info("\n✅ Examples complete!")


if __name__ == "__main__":
    # Run examples
    asyncio.run(example_usage())