"""Same current-position definition across the three owner surfaces."""
import json
import pytest
from test_reporting import calculation, app, RANGE, report
from test_boundaries import client, job, quote, write
from test_documents import doc, edit_payload
from test_recovery import table_rows


def test_overview_matches_reports_without_changing_transferred_history(calculation, app):
    c = calculation['c']
    before = table_rows(app.state.store.root, 'oak')
    workspace = c.get('/api/workspace').json()
    operations = c.get('/api/reports/operations', params=RANGE).json()
    activity = report(c)
    assert operations['current']['open_quote_estimate_pence'] == 12000
    assert activity['totals']['open_quote_estimate_pence'] == 12000
    assert workspace['stats']['quoted_pence'] == 12000
    assert workspace['stats']['open_quote_estimate_pence'] == 12000
    assert workspace['stats']['open_jobs'] == operations['current']['open_jobs'] == activity['totals']['open_jobs'] == 2
    assert workspace['stats']['received_pence'] == 5000  # All dates, not October's 4000.
    assert workspace['stats']['outstanding_pence'] == operations['current']['issued_invoice_balance_pence'] == activity['totals']['issued_invoice_balance_pence'] == 10000
    assert table_rows(app.state.store.root, 'oak') == before


@pytest.mark.parametrize('observed,day,expiry,expected', [
    ('2026-07-15T22:59:59+00:00', '2026-07-15', '2026-07-15', 1234),
    ('2026-07-15T23:00:00+00:00', '2026-07-16', '2026-07-15', 0),
    ('2026-10-28T23:59:59+00:00', '2026-10-28', '2026-10-28', 1234),
    ('2026-10-29T00:00:00+00:00', '2026-10-29', '2026-10-28', 0),
    ('2026-10-29T00:00:00+00:00', '2026-10-29', '', 1234),
])
def test_current_expiry_uses_london_day_in_every_view(app, monkeypatch, observed, day, expiry, expected):
    monkeypatch.setattr('backend.app.today', lambda: day)
    monkeypatch.setattr('backend.operations_report.today', lambda: day)
    monkeypatch.setattr('backend.reporting.now', lambda: observed)
    c = client(app); j = job(c); q = quote(c, j, 1234)
    body = edit_payload(doc(c, 'quote', q)); body['valid_until'] = expiry
    assert write(c, '/api/quotes/' + q['id'], body, method='put').status_code == 200
    for period in (RANGE, dict(start='2026-01-01', end='2026-01-01')):
        a = c.get('/api/reports/activity', params=period).json()
        o = c.get('/api/reports/operations', params=period).json()
        assert a['observation_day'] == o['as_of'] == day
        assert c.get('/api/workspace').json()['stats']['open_quote_estimate_pence'] == o['current']['open_quote_estimate_pence'] == a['totals']['open_quote_estimate_pence'] == expected


def test_unknown_expiry_is_excluded_and_disclosed_without_repairing_history(app):
    c = client(app); j = job(c); q = quote(c, j, 1234)
    # An explicit malformed legacy fixture, never a write to owner data.
    with app.state.store.tenant('oak') as db:
        snapshot = json.loads(db.execute('SELECT snapshot FROM quotes WHERE id=?', (q['id'],)).fetchone()[0])
        snapshot['valid_until'] = 'not-a-date'
        db.execute('UPDATE quotes SET snapshot=? WHERE id=?', (json.dumps(snapshot), q['id']))
    before = table_rows(app.state.store.root, 'oak')
    a = report(c); o = c.get('/api/reports/operations', params=RANGE).json()
    assert c.get('/api/workspace').json()['stats']['open_quote_estimate_pence'] == o['current']['open_quote_estimate_pence'] == a['totals']['open_quote_estimate_pence'] == 0
    assert a['totals']['unknown_dates'] == 1
    assert next(r for r in a['records'] if r['metric']=='unknown_dates')['date_role'] == 'quote expiry'
    assert table_rows(app.state.store.root, 'oak') == before
