"""Quick integration test for v2 changes"""
import sys, os, json
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from app import create_app
from app.extensions import db
from app.models.position import Position
from app.models.user import User

app = create_app()

with app.test_client() as c:
    c.post('/auth/login', data={'email': 'fk@kpt-consulting.de', 'password': 'kpt2024'})

    # 1. Add a custom position
    r = c.post('/projekt/1/1/position/hinzufuegen', data={
        'pos_nr': 'TEST-001', 'kurztext': 'Testposition',
        'einheit': 'ST', 'einzelpreis': '100.00'
    })
    print(f'1. Position hinzufuegen: {r.status_code}')

    # 2. List positions
    r = c.get('/projekt/1/1/positionen')
    data = json.loads(r.data)
    print(f'2. Positionen: {len(data)} found')

    # 3. Update cell
    positions = Position.query.filter_by(aufmass_id=1).all()
    if positions:
        pos_id = positions[0].id
        r = c.post(f'/projekt/1/1/position/{pos_id}/update-cell', json={
            'field': 'menge', 'value': 5.0
        })
        res = json.loads(r.data)
        print(f'3. Update-cell menge: {r.status_code} -> hinten={res.get("menge_hinten")} gp={res.get("gesamtpreis")}')

    # 4. Farben endpoint
    r = c.get('/projekt/1/1/positionen/farben')
    print(f'4. Farben: {r.status_code}')

    # 5. Firmen page
    r = c.get('/admin/firma')
    print(f'5. Firma page: {r.status_code}')

    # 6. Superadmin test
    c.post('/auth/login', data={'email': 'super@admin.de', 'password': 'admin'})
    r = c.get('/superadmin/')
    html = r.data.decode()
    print(f'6. Superadmin dashboard: {r.status_code} (Firmen: {"KPT" in html})')
    
    # 7. Firm detail
    r = c.get('/superadmin/firma/1')
    print(f'7. Firm detail: {r.status_code}')

    # 8. LV page as superadmin
    r = c.get('/lv/')
    print(f'8. LV page: {r.status_code}')

    # 9. Create new aufmass
    c.post('/auth/login', data={'email': 'fk@kpt-consulting.de', 'password': 'kpt2024'})
    r = c.post('/projekt/1/projekt/neu', data={
        'name': 'Teilaufmass 1', 'typ': 'Teilaufmass'
    }, follow_redirects=True)
    print(f'9. Aufmass created: {r.status_code}')

    # 10. List aufmasse
    r = c.get('/projekt/1')
    print(f'10. Aufmass list: {r.status_code}')

    # 11. Check new aufmass in editor
    r = c.get('/projekt/1/2')
    print(f'11. Editor for new aufmass: {r.status_code}')

print('\n=== ALL TESTS PASSED ===')
