#!/usr/bin/env python3
"""
Daily vehicle price tracker for 7-seater MPVs near 90599 Dietenhofen.
Searches mobile.de and autoscout24, saves price history to JSON with listing URL as ID.
Criteria: Benziner, <= 10000 EUR, <= 100000 km, 7 seats, ~50km radius.
"""

import json
import os
import sys
import re
from datetime import datetime
from pathlib import Path
from math import radians, cos, sin, asin, sqrt

# Add hermes tools to path
sys.path.insert(0, '/opt/hermes')

from hermes_tools import web_search, web_extract

# Constants
DATA_FILE = Path('/opt/data/vehicle_price_history.json')
SEARCH_RADIUS_KM = 50
LOCATION = '90599 Dietenhofen'
MAX_PRICE_PRIMARY = 10000   # Primary target
MAX_PRICE_SECONDARY = 15000 # Extended range (acceptable but secondary)
MAX_KM_PRIMARY = 100000     # Primary target
MAX_KM_SECONDARY = 150000   # Extended range (acceptable but secondary)
MIN_POWER_PS = 120
MIN_POWER_KW = 88
MAX_DISTANCE_KM = 100

# Reference coordinates for 90599 Dietenhofen
REF_LAT = 49.4019
REF_LON = 10.7089

# Known location coordinates for major cities in the area (for distance calculation)
CITY_COORDS = {
    'nuernberg': (49.4521, 11.0767),
    'nuremberg': (49.4521, 11.0767),
    'fuerth': (49.4774, 10.9886),
    'erlangen': (49.5898, 11.0078),
    'ansbach': (49.3005, 10.5717),
    'bamberg': (49.8988, 10.9028),
    'bayreuth': (49.9432, 11.5783),
    'coburg': (50.2592, 10.9636),
    'schwabach': (49.3301, 11.0238),
    'fuerth': (49.4774, 10.9886),
    'forchheim': (49.7175, 11.0587),
    'neumarkt': (49.2803, 11.4628),
    'neustadt': (49.5833, 11.1333),
    'roth': (49.2472, 11.0905),
    'windsheim': (49.5025, 10.4042),
    'cadolzburg': (49.4455, 10.8585),
    'rossatal': (49.3833, 10.8667),
    'rossstal': (49.3833, 10.8667),
    'buchschwabach': (49.2989, 11.0172),
    'zirndorf': (49.4424, 10.9541),
    'oberasbach': (49.4194, 10.9594),
    'stein': (49.4128, 11.0083),
    'lauf': (49.5136, 11.2753),
    'herzogenaurach': (49.5689, 10.8875),
    'baiersdorf': (49.6683, 11.0167),
    'dietenhofen': (49.4019, 10.7089),
    'ansbach': (49.3005, 10.5717),
    'feuchtwangen': (49.1667, 10.3167),
    'crailsheim': (49.1344, 10.0719),
    'schwaebisch-hall': (49.1136, 9.7381),
    'heilbronn': (49.1427, 9.2109),
    'wuerzburg': (49.7913, 9.9534),
    'wuerzburg': (49.7913, 9.9534),
    'bamberg': (49.8988, 10.9028),
    'ingolstadt': (48.7665, 11.4258),
    'augsburg': (48.3705, 10.8978),
    'muenchen': (48.1374, 11.5755),
    'munich': (48.1374, 11.5755),
    'stuttgart': (48.7758, 9.1829),
    'frankfurt': (50.1109, 8.6821),
    'leipzig': (51.3397, 12.3731),
    'dresden': (51.0504, 13.7373),
    'berlin': (52.5200, 13.4050),
    'hamburg': (53.5511, 9.9937),
    'koeln': (50.9375, 6.9603),
    'cologne': (50.9375, 6.9603),
    'duesseldorf': (51.2277, 6.7735),
    'duesseldorf': (51.2277, 6.7735),
    'essen': (51.4556, 7.0116),
    'dortmund': (51.5136, 7.4653),
    'bremen': (53.0793, 8.8017),
    'hannover': (52.3759, 9.7320),
}

def haversine(lat1, lon1, lat2, lon2):
    """Calculate distance between two coordinates in km."""
    R = 6371  # Earth radius in km
    dlat = radians(lat2 - lat1)
    dlon = radians(lon2 - lon1)
    a = sin(dlat/2)**2 + cos(radians(lat1)) * cos(radians(lat2)) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    return R * c

def extract_location_and_distance(desc, url):
    """Extract location from description and calculate distance to 90599."""
    location = None
    distance_km = None
    
    # Try to extract PLZ (5 digits) from description
    plz_match = re.search(r'\b(\d{5})\b', desc)
    if plz_match:
        plz = plz_match.group(1)
        # Check if it's a known city PLZ
        for city, coords in CITY_COORDS.items():
            # Simple heuristic: if PLZ starts with city prefix or is in range
            # For now, use city name matching from description
            pass
    
    # Try to find city name in description
    desc_lower = desc.lower()
    for city, coords in CITY_COORDS.items():
        if city in desc_lower:
            location = city.title()
            distance_km = round(haversine(REF_LAT, REF_LON, coords[0], coords[1]))
            break
    
    # Also check URL for location hints
    if not location:
        url_lower = url.lower()
        for city, coords in CITY_COORDS.items():
            if city in url_lower:
                location = city.title()
                distance_km = round(haversine(REF_LAT, REF_LON, coords[0], coords[1]))
                break
    
    # If still no location, try to extract from common patterns
    if not location:
        # Look for "DE-XXXXX City" pattern
        loc_match = re.search(r'DE-(\d{5})\s*([A-Za-zäöüÄÖÜß\s-]+)', desc)
        if loc_match:
            location = loc_match.group(2).strip().title()
            # Try to get coords from PLZ prefix
            plz_prefix = loc_match.group(1)[:2]
            # Rough mapping
            plz_to_city = {
                '90': 'Nürnberg', '91': 'Ansbach', '92': 'Weiden', '93': 'Regensburg',
                '94': 'Passau', '95': 'Hof', '96': 'Bamberg', '97': 'Würzburg',
                '98': 'Suhl', '99': 'Erfurt', '80': 'München', '81': 'München',
                '82': 'Starnberg', '83': 'Rosenheim', '84': 'Landshut', '85': 'Freising',
                '86': 'Augsburg', '87': 'Kempten', '88': 'Ravensburg', '89': 'Ulm',
            }
            if plz_prefix in plz_to_city:
                city = plz_to_city[plz_prefix].lower()
                if city in CITY_COORDS:
                    distance_km = round(haversine(REF_LAT, REF_LON, CITY_COORDS[city][0], CITY_COORDS[city][1]))
    
    return location, distance_km

# Models to track (similar size to Zafira C Tourer) - 7-seater MPVs available in Germany
# Using URL slugs as used on mobile.de and autoscout24
MODELS = [
    # Opel
    {'brand': 'opel', 'model': 'zafira-tourer', 'label': 'Opel Zafira Tourer'},
    {'brand': 'opel', 'model': 'zafira-c-tourer', 'label': 'Opel Zafira C Tourer'},
    {'brand': 'opel', 'model': 'zafira-life', 'label': 'Opel Zafira Life'},  # successor, van-based but 7-9 seats
    
    # Ford (S-Max/Galaxy/Grand C-Max share platform with VW Sharan/Seat Alhambra)
    {'brand': 'ford', 'model': 's-max', 'label': 'Ford S-Max'},
    {'brand': 'ford', 'model': 'galaxy', 'label': 'Ford Galaxy'},  # larger brother of S-Max
    {'brand': 'ford', 'model': 'grand-c-max', 'label': 'Ford Grand C-Max'},
    
    # Volkswagen Group (Sharan/Alhambra = same platform)
    {'brand': 'volkswagen', 'model': 'touran', 'label': 'VW Touran'},
    {'brand': 'volkswagen', 'model': 'sharan', 'label': 'VW Sharan'},
    {'brand': 'seat', 'model': 'alhambra', 'label': 'Seat Alhambra'},
    
    # Stellantis (Peugeot/Citroën/Opel)
    {'brand': 'peugeot', 'model': '5008', 'label': 'Peugeot 5008'},
    {'brand': 'citroen', 'model': 'grand-c4-picasso', 'label': 'Citroën Grand C4 Picasso'},
    {'brand': 'citroen', 'model': 'c4-spacetourer', 'label': 'Citroën C4 SpaceTourer'},  # successor to Grand C4 Picasso
    {'brand': 'citroen', 'model': 'grand-c4-spacetourer', 'label': 'Citroën Grand C4 SpaceTourer'},
    
    # Renault
    {'brand': 'renault', 'model': 'grand-scenic', 'label': 'Renault Grand Scénic'},
    {'brand': 'renault', 'model': 'espace', 'label': 'Renault Espace'},  # older gens (IV/V) might fit budget
    
    # Kia/Hyundai
    {'brand': 'kia', 'model': 'carens', 'label': 'Kia Carens'},
    {'brand': 'hyundai', 'model': 'ix35', 'label': 'Hyundai ix35'},  # compact SUV, some 7-seat versions
    
    # Toyota
    {'brand': 'toyota', 'model': 'verso', 'label': 'Toyota Verso'},  # compact MPV, 7 seats
    {'brand': 'toyota', 'model': 'prius-plus', 'label': 'Toyota Prius+'},  # hybrid MPV, 7 seats
    
    # Mazda
    {'brand': 'mazda', 'model': '5', 'label': 'Mazda 5'},  # sold as Premacy in some markets
    
    # BMW/Mercedes (compact MPVs with 7 seats)
    {'brand': 'bmw', 'model': '2er-gran-tourer', 'label': 'BMW 2er Gran Tourer'},
    {'brand': 'mercedes-benz', 'model': 'b-klasse', 'label': 'Mercedes B-Klasse'},  # only 5 seats mostly, but check
    
    # Chrysler (older models cheap)
    {'brand': 'chrysler', 'model': 'grand-voyager', 'label': 'Chrysler Grand Voyager'},
    
    # Van-based / Ludospace (7 seats, different character but relevant for some buyers)
    {'brand': 'volkswagen', 'model': 'caddy-maxi', 'label': 'VW Caddy Maxi'},
    {'brand': 'citroen', 'model': 'berlingo', 'label': 'Citroën Berlingo'},
    {'brand': 'peugeot', 'model': 'rifter', 'label': 'Peugeot Rifter'},
    {'brand': 'opel', 'model': 'combo-life', 'label': 'Opel Combo Life'},
    {'brand': 'toyota', 'model': 'proace-verso', 'label': 'Toyota ProAce Verso'},
]

def load_existing_data():
    """Load existing price history from JSON file."""
    if DATA_FILE.exists():
        try:
            with open(DATA_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        except json.JSONDecodeError:
            print("Warning: Could not parse existing JSON, starting fresh")
    return {}

def save_data(data):
    """Save price history to JSON file."""
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def search_mobile_de(model):
    """Search mobile.de for a specific model."""
    brand = model['brand']
    model_name = model['model']
    label = model['label']
    
    query = f'site:mobile.de {label} Benzin 90599 Dietenhofen 50km'
    print(f"  Searching mobile.de: {label}")
    
    try:
        result = web_search(query=query, limit=20)
        listings = []
        for item in result.get('data', {}).get('web', []):
            # Extract basic info from snippet
            url = item.get('url', '')
            title = item.get('title', '')
            desc = item.get('description', '')
            
            # Try to extract price, km, year from description
            price_match = re.search(r'(\d[\d.,]*)\s*€', desc)
            km_match = re.search(r'(\d[\d.,]*)\s*km', desc)
            year_match = re.search(r'(EZ\s*)?(\d{2}/\d{4}|\d{4})', desc)
            power_match = re.search(r'(\d+)\s*kW\s*\((\d+)\s*PS\)', desc)
            
            # Extract location and distance
            location, distance_km = extract_location_and_distance(desc, url)
            
            listing = {
                'url': url,
                'title': title,
                'source': 'mobile.de',
                'model': label,
                'price_eur': int(price_match.group(1).replace('.', '').replace(',', '')) if price_match else None,
                'mileage_km': int(km_match.group(1).replace('.', '').replace(',', '')) if km_match else None,
                'year': year_match.group(2) if year_match else None,
                'power_kw': int(power_match.group(1)) if power_match else None,
                'power_ps': int(power_match.group(2)) if power_match else None,
                'location': location,
                'distance_km': distance_km,
                'raw_description': desc[:500],
                'first_seen': datetime.now().isoformat(),
                'last_seen': datetime.now().isoformat(),
                'price_history': []
            }
            
            # Initialize price history
            if listing['price_eur']:
                listing['price_history'].append({
                    'date': datetime.now().date().isoformat(),
                    'price_eur': listing['price_eur']
                })
            
            listings.append(listing)
        
        return listings
    except Exception as e:
        print(f"    Error searching mobile.de for {label}: {e}")
        return []

def search_autoscout24(model):
    """Search autoscout24 for a specific model."""
    brand = model['brand']
    model_name = model['model']
    label = model['label']
    
    query = f'site:autoscout24.de {label} Benzin 90599 Dietenhofen 50km'
    print(f"  Searching autoscout24: {label}")
    
    try:
        result = web_search(query=query, limit=20)
        listings = []
        for item in result.get('data', {}).get('web', []):
            url = item.get('url', '')
            title = item.get('title', '')
            desc = item.get('description', '')
            
            price_match = re.search(r'€\s*(\d[\d.,]*)', desc)
            km_match = re.search(r'(\d[\d.,]*)\s*km', desc)
            year_match = re.search(r'(\d{2}/\d{4})', desc)
            power_match = re.search(r'(\d+)\s*kW\s*\((\d+)\s*PS\)', desc)
            
            # Extract location and distance
            location, distance_km = extract_location_and_distance(desc, url)
            
            listing = {
                'url': url,
                'title': title,
                'source': 'autoscout24',
                'model': label,
                'price_eur': int(price_match.group(1).replace('.', '').replace(',', '')) if price_match else None,
                'mileage_km': int(km_match.group(1).replace('.', '').replace(',', '')) if km_match else None,
                'year': year_match.group(1) if year_match else None,
                'power_kw': int(power_match.group(1)) if power_match else None,
                'power_ps': int(power_match.group(2)) if power_match else None,
                'location': location,
                'distance_km': distance_km,
                'raw_description': desc[:500],
                'first_seen': datetime.now().isoformat(),
                'last_seen': datetime.now().isoformat(),
                'price_history': []
            }
            
            if listing['price_eur']:
                listing['price_history'].append({
                    'date': datetime.now().date().isoformat(),
                    'price_eur': listing['price_eur']
                })
            
            listings.append(listing)
        
        return listings
    except Exception as e:
        print(f"    Error searching autoscout24 for {label}: {e}")
        return []

def filter_listings(listings):
    """Filter listings by criteria."""
    filtered = []
    for l in listings:
        # Must have price and mileage
        if not l.get('price_eur') or not l.get('mileage_km'):
            continue
        
        price = l['price_eur']
        # Price: primary <= 10k, secondary up to 15k
        if price > MAX_PRICE_SECONDARY:
            continue
        
        mileage = l['mileage_km']
        # Mileage: primary <= 100k, secondary up to 150k
        if mileage > MAX_KM_SECONDARY:
            continue
        
        # Benziner is mandatory - check description for benziner/benzin
        desc = l.get('raw_description', '').lower()
        if 'benziner' not in desc and 'benzin' not in desc:
            continue
        
        # Hard requirements: Sitzheizung and Tempomat
        if 'sitzheizung' not in desc and 'sitzheiz.' not in desc:
            continue
        if 'tempomat' not in desc and 'geschwindigkeitsregel' not in desc and 'cruise control' not in desc and 'cruise-control' not in desc:
            continue
        
        # Minimum power: 120 PS / 88 kW
        power_ps = l.get('power_ps')
        power_kw = l.get('power_kw')
        if power_ps is not None and power_ps < MIN_POWER_PS:
            continue
        if power_kw is not None and power_kw < MIN_POWER_KW:
            continue
        
        # Distance filter: max ~100km from 90599
        distance = l.get('distance_km')
        if distance is not None and distance > MAX_DISTANCE_KM:
            continue
        
        # Mark priority
        if price <= MAX_PRICE_PRIMARY:
            l['price_priority'] = 'primary'
        else:
            l['price_priority'] = 'secondary'
            
        if mileage <= MAX_KM_PRIMARY:
            l['mileage_priority'] = 'primary'
        else:
            l['mileage_priority'] = 'secondary'
        
        filtered.append(l)
    return filtered

def merge_listings(existing_data, new_listings):
    """Merge new listings into existing data, updating price history."""
    now = datetime.now().date().isoformat()
    
    for listing in new_listings:
        url = listing['url']
        
        if url in existing_data:
            # Update existing entry
            existing = existing_data[url]
            existing['last_seen'] = datetime.now().isoformat()
            
            # Update current price/mileage if changed
            if listing.get('price_eur') and listing['price_eur'] != existing.get('price_eur'):
                existing['price_eur'] = listing['price_eur']
                existing['price_history'].append({
                    'date': now,
                    'price_eur': listing['price_eur']
                })
            
            if listing.get('mileage_km'):
                existing['mileage_km'] = listing['mileage_km']
            
            # Update other fields if newly available
            for key in ['year', 'power_kw', 'power_ps', 'title']:
                if listing.get(key) and not existing.get(key):
                    existing[key] = listing[key]
        else:
            # New listing
            existing_data[url] = listing
    
    return existing_data

def main():
    print(f"=== Vehicle Price Tracker - {datetime.now().isoformat()} ===")
    print(f"Location: {LOCATION}, Radius: {SEARCH_RADIUS_KM}km")
    print(f"Criteria: Benziner, <= {MAX_PRICE_PRIMARY}..{MAX_PRICE_SECONDARY} EUR, <= {MAX_KM_PRIMARY}..{MAX_KM_SECONDARY} km, >= {MIN_POWER_PS} PS, <= {MAX_DISTANCE_KM} km")
    print()
    
    # Load existing data
    data = load_existing_data()
    print(f"Loaded {len(data)} existing listings")
    
    all_new_listings = []
    
    # Search each model on both platforms
    for model in MODELS:
        mobile_listings = search_mobile_de(model)
        auto_listings = search_autoscout24(model)
        
        all_new_listings.extend(mobile_listings)
        all_new_listings.extend(auto_listings)
    
    # Filter by criteria
    filtered = filter_listings(all_new_listings)
    print(f"\nFound {len(all_new_listings)} total listings, {len(filtered)} match criteria")
    
    # Merge into existing data
    data = merge_listings(data, filtered)
    
    # Save
    save_data(data)
    print(f"Saved {len(data)} total listings to {DATA_FILE}")
    
    # Print summary of matches
    print("\n--- Current Matches ---")
    for url, listing in data.items():
        if listing.get('price_eur') and listing['price_eur'] <= MAX_PRICE_SECONDARY and listing.get('mileage_km', 0) <= MAX_KM_SECONDARY:
            history = listing.get('price_history', [])
            price_trend = " → ".join(str(h['price_eur']) for h in history[-3:]) if history else "N/A"
            prio_price = listing.get('price_priority', '?')
            prio_mileage = listing.get('mileage_priority', '?')
            print(f"  {listing['model']} | {listing['price_eur']} € ({prio_price}) | {listing['mileage_km']} km ({prio_mileage}) | {listing.get('power_ps', '?')} PS | {listing.get('location', '?')} ({listing.get('distance_km', '?')} km) | {listing['source']} | Trend: {price_trend}")
            print(f"    {url}")

if __name__ == '__main__':
    main()