"""Automated basic end-to-end test for Phase 1 features.
Creates a project, updates settings, uploads an image, lists media, deletes image.
"""
import io
import os
import sys
import time
import json
import requests
from PIL import Image

BASE = 'http://127.0.0.1:5000'

def create_project(name='test-project'):
    r = requests.post(f'{BASE}/api/projects', json={'name': name, 'description': 'automated test'})
    r.raise_for_status()
    return r.json()

def update_settings(slug):
    r = requests.put(f'{BASE}/api/projects/{slug}/settings', json={'title':'Auto Test','description':'desc'})
    r.raise_for_status()
    return r.json()

def upload_image(slug):
    # generate small PNG
    im = Image.new('RGB', (100,100), color=(123,222,100))
    buf = io.BytesIO()
    im.save(buf, format='PNG')
    buf.seek(0)
    files = {'file': ('test.png', buf, 'image/png')}
    r = requests.post(f'{BASE}/api/projects/{slug}/media/upload', files=files)
    r.raise_for_status()
    return r.json()

def list_media(slug):
    r = requests.get(f'{BASE}/api/projects/{slug}/media/list')
    r.raise_for_status()
    return r.json()

def delete_media(slug, rel):
    r = requests.delete(f'{BASE}/api/projects/{slug}/media/{rel}')
    return r

if __name__ == '__main__':
    print('Creating project...')
    proj = create_project('phase1-e2e')
    slug = proj['slug']
    print('Project created:', slug)
    print('Updating settings...')
    print(update_settings(slug))
    print('Uploading image...')
    up = upload_image(slug)
    print('Upload result:', up)
    time.sleep(0.5)
    items = list_media(slug)
    print('Media list count:', len(items))
    if items:
        it = items[0]
        rel = f"media/images/{it['date']}/{it['filename']}"
        print('Deleting', rel)
        r = delete_media(slug, rel)
        print('Delete status', r.status_code)
    print('Done')
