import pytest
import os
from flask import Flask
from api.task_api import task_api
from db.db import task_db, child_db
from tinydb import Query

@pytest.fixture
def client():
    app = Flask(__name__)
    app.register_blueprint(task_api)
    app.config['TESTING'] = True
    with app.test_client() as client:
        yield client

@pytest.fixture(scope="session", autouse=True)
def cleanup_db():
    yield
    task_db.close()
    if os.path.exists('tasks.json'):
        os.remove('tasks.json')

def test_add_task(client):
    response = client.put('/task/add', json={'name': 'Clean Room', 'points': 10, 'is_good': True})
    assert response.status_code == 201
    assert b'Task Clean Room added.' in response.data
    # verify in database
    tasks = task_db.all()
    assert any(task.get('name') == 'Clean Room' and task.get('points') == 10 and task.get('is_good') is True and task.get('image_id') == '' for task in tasks)

    response = client.put('/task/add', json={'name': 'Eat Dinner', 'points': 5, 'is_good': False, 'image_id': 'meal'})
    assert response.status_code == 201
    assert b'Task Eat Dinner added.' in response.data
    # verify in database
    tasks = task_db.all()
    assert any(task.get('name') == 'Eat Dinner' and task.get('points') == 5 and task.get('is_good') is False and task.get('image_id') == 'meal' for task in tasks)



def test_list_tasks(client):
    task_db.truncate()
    task_db.insert({'id': 't1', 'name': 'Task1', 'points': 5, 'is_good': True})
    task_db.insert({'id': 't2', 'name': 'Task2', 'points': 15, 'is_good': False, 'image_id': 'meal'})
    response = client.get('/task/list')
    assert response.status_code == 200
    assert b'tasks' in response.data
    data = response.json
    assert len(data['tasks']) == 2


def test_get_task_not_found(client):
    response = client.get('/task/nonexistent-id')
    assert response.status_code == 404
    assert b'Task not found' in response.data

def test_delete_task_not_found(client):
    response = client.delete('/task/nonexistent-id')
    assert response.status_code == 404
    assert b'Task not found' in response.data

def test_delete_assigned_task_removes_from_child(client):
    # create task and child with the task already assigned
    task_db.insert({'id': 't_delete_assigned', 'name': 'Temp Task', 'points': 5, 'is_good': True})
    child_db.insert({
        'id': 'child_for_task_delete',
        'name': 'Frank',
        'age': 7,
        'points': 0,
        'tasks': ['t_delete_assigned'],
        'rewards': []
    })

    ChildQuery = Query()
    # precondition: child has the task
    assert 't_delete_assigned' in child_db.search(ChildQuery.id == 'child_for_task_delete')[0].get('tasks', [])

    # call the delete endpoint
    resp = client.delete('/task/t_delete_assigned')
    assert resp.status_code == 200

    # verify the task id is no longer in the child's tasks
    child = child_db.search(ChildQuery.id == 'child_for_task_delete')[0]
    assert 't_delete_assigned' not in child.get('tasks', [])