#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import sys
import logging
from datetime import datetime
import socket
import json
import requests
from collections import defaultdict
from datetime import datetime, date

# Add project path to system path
project_path = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, project_path)

print("=" * 50)
print("🤖 AmlakJame Bot Starting...")
print("=" * 50)
print(f"📁 Project path: {project_path}")
print(f"📂 Working directory: {os.getcwd()}")

# Load environment variables
from dotenv import load_dotenv

# Load .env file
env_path = os.path.join(project_path, '.env')
print(f"🔍 Looking for .env at: {env_path}")

if os.path.exists(env_path):
    print("✅ .env file found")
    load_dotenv(dotenv_path=env_path)
else:
    print("❌ .env file NOT found!")
    print("Creating default .env file...")
    with open('.env', 'w') as f:
        f.write("BOT_TOKEN=your_bot_token_here\n")
        f.write("API_BASE_URL=https://amlakjame.ir\n")
    print("📄 Created default .env file. Please edit it with your token.")
    sys.exit(1)

# Get bot token
BOT_TOKEN = os.getenv('BOT_TOKEN')

if not BOT_TOKEN or BOT_TOKEN == 'your_bot_token_here':
    print("\n❌ ERROR: BOT_TOKEN is not set correctly!")
    print("Please edit the .env file and add your bot token.")
    print("Format: BOT_TOKEN=your_actual_bot_token_here")
    print(f"📄 .env file location: {env_path}")
    sys.exit(1)

# Mask token for security
masked_token = BOT_TOKEN[:8] + "..." + BOT_TOKEN[-4:] if len(BOT_TOKEN) > 12 else "***"
print(f"✅ Bot token loaded: {masked_token}")

# Get other settings with defaults
API_BASE_URL = os.getenv('API_BASE_URL', 'https://amlakjame.ir')
print(f"🌐 API URL: {API_BASE_URL}")

# Setup logging
LOG_DIR = os.path.join(project_path, 'logs')
if not os.path.exists(LOG_DIR):
    os.makedirs(LOG_DIR)
    print(f"📁 Created logs directory: {LOG_DIR}")

logging.basicConfig(
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    level=logging.INFO,
    handlers=[
        logging.FileHandler(os.path.join(LOG_DIR, 'bot.log'), encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

print("✅ Logging setup complete")
print("=" * 50)

# Check Python version
if sys.version_info < (3, 7):
    logger.error("❌ Python 3.7 or higher is required")
    sys.exit(1)

# Import telegram modules
try:
    from telegram import Update, ReplyKeyboardMarkup, KeyboardButton, ReplyKeyboardRemove
    from telegram.ext import (
        Updater, CommandHandler, MessageHandler, Filters, 
        CallbackContext, ConversationHandler
    )
    print("✅ Telegram libraries imported successfully")
except ImportError as e:
    logger.error(f"❌ Failed to import telegram libraries: {e}")
    print("Please install: pip install python-telegram-bot==13.15")
    sys.exit(1)

# Rest of your code continues here...