import os
import platform
from datetime import date, timedelta
from django.shortcuts import render
from django.utils import timezone
from .models import MemberOfParliament, TradeDisclosure

def home(request):
    """Render the landing screen with MP trades and environment details."""
    
    # Seed data if empty
    if not MemberOfParliament.objects.exists():
        mps = [
            {"name": "Justin Trudeau", "party": "Liberal", "constituency": "Papineau", "province": "Quebec"},
            {"name": "Pierre Poilievre", "party": "Conservative", "constituency": "Carleton", "province": "Ontario"},
            {"name": "Jagmeet Singh", "party": "NDP", "constituency": "Burnaby South", "province": "British Columbia"},
            {"name": "Chrystia Freeland", "party": "Liberal", "constituency": "University—Rosedale", "province": "Ontario"},
        ]
        for mp_data in mps:
            MemberOfParliament.objects.get_or_create(**mp_data)
        
        mp_jt = MemberOfParliament.objects.get(name="Justin Trudeau")
        mp_pp = MemberOfParliament.objects.get(name="Pierre Poilievre")
        
        TradeDisclosure.objects.get_or_create(
            mp=mp_jt, ticker="AAPL", company_name="Apple Inc.", 
            trade_type="BUY", amount_range="$15,001 - $50,000", 
            disclosure_date=date.today() - timedelta(days=2)
        )
        TradeDisclosure.objects.get_or_create(
            mp=mp_pp, ticker="SHOP", company_name="Shopify Inc.", 
            trade_type="SELL", amount_range="$50,001 - $100,000", 
            disclosure_date=date.today() - timedelta(days=5)
        )
        TradeDisclosure.objects.get_or_create(
            mp=mp_jt, ticker="TSLA", company_name="Tesla, Inc.", 
            trade_type="BUY", amount_range="$1,000 - $15,000", 
            disclosure_date=date.today() - timedelta(days=10)
        )

    trades = TradeDisclosure.objects.select_related('mp').order_by('-disclosure_date')[:10]
    total_trades = TradeDisclosure.objects.count()
    total_mps = MemberOfParliament.objects.count()
    
    context = {
        "project_name": "Canada MP Trade Tracker",
        "trades": trades,
        "total_trades": total_trades,
        "total_mps": total_mps,
        "current_time": timezone.now(),
    }
    return render(request, "core/index.html", context)

def mp_list(request):
    """Render a list of all Members of Parliament."""
    mps = MemberOfParliament.objects.all().order_by('name')
    context = {
        "project_name": "Canada MP Trade Tracker",
        "mps": mps,
    }
    return render(request, "core/mp_list.html", context)