# python
# File: db/debug.py

from tinydb import Query
import os
import shutil

from api.image_api import IMAGE_TYPE_ICON, IMAGE_TYPE_PROFILE
from config.paths import get_images_dir
from db.db import task_db, reward_db, image_db
from models.image import Image
from models.reward import Reward
from models.task import Task
import logging

logger = logging.getLogger(__name__)


def populate_default_data():
    # Create tasks
    task_defs = [
        ('default_001', "Be Respectful", 2, 'chore', ''),
        ('default_002', "Brush Teeth", 2, 'chore', ''),
        ('default_003', "Go To Bed", 2, 'chore', ''),
        ('default_004', "Do What You Are Told", 2, 'chore', ''),
        ('default_005', "Make Your Bed", 2, 'chore', ''),
        ('default_006', "Do Homework", 2, 'chore', ''),
    ]
    tasks = []
    for _id, name, points, task_type, image in task_defs:
        t = Task(name=name, points=points, type=task_type, image_id=image, id=_id)
        tq = Query()
        _result = task_db.search(tq.id == _id)
        if not _result:
            task_db.insert(t.to_dict())
        else:
            task_db.update(t.to_dict(), tq.id == _id)
        tasks.append(t.to_dict())

    # Create 4 rewards
    reward_defs = [
        ('default_001', "Special Trip", "Go to a park or a museum", 3,''),
        ('default_002', "Money", "Money is always nice", 8, ''),
        ('default_003', "Choose Dinner", "What shall we eat?", 12, 'meal'),
        ('default_004', "Tablet Time", "Play your games", 5, 'tablet'),
        ('default_005', "Computer Time", "Minecraft or Roblox?", 5, 'computer-game'),
        ('default_006', "TV Time", "Too much is bad for you.", 5, ''),
    ]
    rewards = []
    for _id, name, desc, cost, image in reward_defs:
        r = Reward(name=name, description=desc, cost=cost, image_id=image, id=_id)
        rq = Query()
        _result = reward_db.search(rq.id == _id)
        if not _result:
            reward_db.insert(r.to_dict())
        else:
            reward_db.update(r.to_dict(), rq.id == _id)
        rewards.append(r.to_dict())

    image_defs = [
        ('computer-game', IMAGE_TYPE_ICON, '.png', True),
        ('ice-cream', IMAGE_TYPE_ICON, '.png', True),
        ('meal', IMAGE_TYPE_ICON, '.png', True),
        ('playground', IMAGE_TYPE_ICON, '.png', True),
        ('tablet', IMAGE_TYPE_ICON, '.png', True),
        ('boy01', IMAGE_TYPE_PROFILE, '.png', True),
        ('girl01', IMAGE_TYPE_PROFILE, '.png', True),
        ('girl02', IMAGE_TYPE_PROFILE, '.png', True),
        ('boy02', IMAGE_TYPE_PROFILE, '.png', True),
        ('boy03', IMAGE_TYPE_PROFILE, '.png', True),
        ('girl03', IMAGE_TYPE_PROFILE, '.png', True),
        ('boy04', IMAGE_TYPE_PROFILE, '.png', True),
        ('girl04', IMAGE_TYPE_PROFILE, '.png', True),
    ]
    images = []
    for _id, _type, ext, perm in image_defs:
        iq = Query()
        _result = image_db.search(iq.id == _id)
        if not _result:
            image_db.insert(Image(_type, ext, perm, id=_id).to_dict())
        else:
            image_db.update(Image(_type, ext, perm, id=_id).to_dict(), iq.id == _id)
        images.append(Image(_type, ext, perm, id=_id).to_dict())

    return {
        "images": images,
        "tasks": tasks,
        "rewards": rewards
    }

def createDefaultTasks():
    """Create default tasks if none exist."""
    if len(task_db.all()) == 0:
        default_tasks = [
            Task(name="Take out trash", points=20, type='chore', image_id="trash-can"),
            Task(name="Make your bed", points=25, type='chore', image_id="make-the-bed"),
            Task(name="Sweep and clean kitchen", points=15, type='chore', image_id="vacuum"),
            Task(name="Do homework early", points=30, type='chore', image_id="homework"),
            Task(name="Be good for the day", points=15, type='kindness', image_id="good"),
            Task(name="Clean your mess", points=20, type='chore', image_id="broom"),

            Task(name="Fighting", points=10, type='penalty', image_id="fighting"),
            Task(name="Yelling at parents", points=10, type='penalty', image_id="yelling"),
            Task(name="Lying", points=10, type='penalty', image_id="lying"),
            Task(name="Not doing what told", points=5, type='penalty', image_id="ignore"),
            Task(name="Not flushing toilet", points=5, type='penalty', image_id="toilet"),
        ]
        for task in default_tasks:
            task_db.insert(task.to_dict())

def createDefaultRewards():
    """Create default rewards if none exist."""
    if len(reward_db.all()) == 0:
        default_rewards = [
            Reward(name="Choose meal", description="Choose dinner or lunch", cost=30, image_id="meal"),
            Reward(name="$1", description="Money is always nice", cost=35, image_id='money'),
            Reward(name="$5", description="Even more money", cost=120, image_id='money'),
            Reward(name="Tablet 1 hour", description="Play your games", cost=50, image_id='tablet'),
            Reward(name="Computer with dad", description="Let's play a game together", cost=50, image_id='games-with-dad'),
            Reward(name="Computer 1 hour", description="Minecraft or Terraria?", cost=50, image_id='computer-game'),
            Reward(name="TV 1 hour", description="Too much is bad for you.", cost=40, image_id='tv'),
            Reward(name="Candy from store", description="Yum!", cost=70, image_id='candy'),
        ]
        for reward in default_rewards:
            reward_db.insert(reward.to_dict())

def initializeImages():
    
    """Initialize the image database with default images if empty, and copy images to data/images/default."""
     # Step 1: Create data/images/default directory if it doesn't exist
    default_img_dir = os.path.join(get_images_dir(), 'default')
    logger.info(f"Initializing images. Ensuring directory exists: {default_img_dir}")
    os.makedirs(default_img_dir, exist_ok=True)

    # Step 2: Copy all image files from resources/images/ to data/images/default
    src_img_dir = os.path.join(os.path.dirname(__file__), '../resources/images')
    if os.path.exists(src_img_dir):
        for fname in os.listdir(src_img_dir):
            src_path = os.path.join(src_img_dir, fname)
            dst_path = os.path.join(default_img_dir, fname)
            if os.path.isfile(src_path):
                shutil.copy2(src_path, dst_path)

    # Original DB initialization logic
    if len(image_db.all()) == 0:
        image_defs = [
            ('boy01', IMAGE_TYPE_PROFILE, '.png', True),
            ('boy02', IMAGE_TYPE_PROFILE, '.png', True),
            ('boy03', IMAGE_TYPE_PROFILE, '.png', True),
            ('boy04', IMAGE_TYPE_PROFILE, '.png', True),
            ('broom', IMAGE_TYPE_ICON, '.png', True),
            ('candy', IMAGE_TYPE_ICON, '.png', True),
            ('computer-game', IMAGE_TYPE_ICON, '.png', True),
            ('fighting', IMAGE_TYPE_ICON, '.png', True),
            ('games-with-dad', IMAGE_TYPE_ICON, '.png', True),
            ('girl01', IMAGE_TYPE_PROFILE, '.png', True),
            ('girl02', IMAGE_TYPE_PROFILE, '.png', True),
            ('girl03', IMAGE_TYPE_PROFILE, '.png', True),
            ('girl04', IMAGE_TYPE_PROFILE, '.png', True),
            ('good', IMAGE_TYPE_ICON, '.png', True),
            ('homework', IMAGE_TYPE_ICON, '.png', True),
            ('ice-cream', IMAGE_TYPE_ICON, '.png', True),
            ('ignore', IMAGE_TYPE_ICON, '.png', True),
            ('lying', IMAGE_TYPE_ICON, '.png', True),
            ('make-the-bed', IMAGE_TYPE_ICON, '.png', True),
            ('meal', IMAGE_TYPE_ICON, '.png', True),
            ('money', IMAGE_TYPE_ICON, '.png', True),
            ('playground', IMAGE_TYPE_ICON, '.png', True),
            ('tablet', IMAGE_TYPE_ICON, '.png', True),
            ('toilet', IMAGE_TYPE_ICON, '.png', True),
            ('trash-can', IMAGE_TYPE_ICON, '.png', True),
            ('tv', IMAGE_TYPE_ICON, '.png', True),
            ('vacuum', IMAGE_TYPE_ICON, '.png', True),
            ('yelling', IMAGE_TYPE_ICON, '.png', True),
        ]
        for _id, _type, ext, perm in image_defs:
            img = Image(type=_type, extension=ext, permanent=perm)
            img.id = _id
            image_db.insert(img.to_dict())

if __name__ == "__main__":
    result = populate_default_data()
