"""Simple Flask API to serve Funda listings"""
from flask import Flask, jsonify, request
from datetime import datetime, date
import json
import os

app = Flask(__name__)

LISTINGS_FILE = '/root/funda.leads/listings.json'

@app.route('/funda-today', methods=['GET'])
def get_today_listings():
    """Get today's Funda listings"""
    try:
        with open(LISTINGS_FILE, 'r') as f:
            listings = json.load(f)
    except FileNotFoundError:
        return jsonify({'error': 'No listings file found'}), 404
    except json.JSONDecodeError:
        return jsonify({'error': 'Invalid listings file'}), 500
    
    today = date.today()
    filtered = []
    for listing in listings:
        if not listing.get('publish_date'):
            continue
        try:
            pub_str = listing['publish_date'].split('T')[0]
            pub_date = datetime.strptime(pub_str, '%Y-%m-%d').date()
            if pub_date == today:
                filtered.append(listing)
        except (ValueError, KeyError):
            continue
    
    return jsonify({
        'count': len(filtered),
        'date': str(today),
        'listings': filtered
    })

@app.route('/funda', methods=['GET'])
def get_listings():
    """
    Get Funda listings.
    
    Query params:
        date: Filter by publish date (YYYY-MM-DD format)
        from: Filter listings from this date onwards (YYYY-MM-DD)
        to: Filter listings up to this date (YYYY-MM-DD)
    
    Examples:
        /funda - All listings
        /funda?date=2026-01-12 - Only listings from Jan 12, 2026
        /funda?from=2026-01-10&to=2026-01-12 - Listings between dates
    """
    try:
        with open(LISTINGS_FILE, 'r') as f:
            listings = json.load(f)
    except FileNotFoundError:
        return jsonify({'error': 'No listings file found'}), 404
    except json.JSONDecodeError:
        return jsonify({'error': 'Invalid listings file'}), 500
    
    # Date filtering
    date_filter = request.args.get('date')
    from_date = request.args.get('from')
    to_date = request.args.get('to')
    
    if date_filter or from_date or to_date:
        filtered = []
        for listing in listings:
            if not listing.get('publish_date'):
                continue
            
            try:
                # Parse publish date (format: 2026-01-12T13:37:27.3600000+01:00)
                pub_str = listing['publish_date'].split('T')[0]
                pub_date = datetime.strptime(pub_str, '%Y-%m-%d').date()
                
                # Exact date filter
                if date_filter:
                    filter_date = datetime.strptime(date_filter, '%Y-%m-%d').date()
                    if pub_date != filter_date:
                        continue
                
                # From date filter
                if from_date:
                    from_dt = datetime.strptime(from_date, '%Y-%m-%d').date()
                    if pub_date < from_dt:
                        continue
                
                # To date filter
                if to_date:
                    to_dt = datetime.strptime(to_date, '%Y-%m-%d').date()
                    if pub_date > to_dt:
                        continue
                
                filtered.append(listing)
            except (ValueError, KeyError):
                continue
        
        listings = filtered
    
    return jsonify({
        'count': len(listings),
        'listings': listings
    })

@app.route('/funda/health', methods=['GET'])
def health():
    """Health check endpoint"""
    return jsonify({'status': 'ok'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
