"""Capture the real Kellen Finance UI using entirely synthetic API responses.

Run the reviewed finance checkout (986e667) on an isolated local port, then:
python scripts/finance/capture.py --url http://127.0.0.1:3105
Requires Playwright and Chrome. Does not connect banks, read statements, or alter
finance source code. All /api requests are intercepted before reaching the app.
"""
import argparse
import json
from pathlib import Path
from playwright.sync_api import sync_playwright

ROOT = Path(__file__).resolve().parents[2]
ASSETS = ROOT / 'projects/finance-dashboard/assets'


def make_demo():
    accounts = []
    for ident, name, kind, balance in [
        ('demo-checking', 'Demo Checking', 'cash', 8200),
        ('demo-savings', 'Demo Savings', 'cash', 12500),
        ('demo-card', 'Demo Credit Card', 'credit', 1600),
        ('demo-brokerage', 'Demo Brokerage', 'investment', 24500),
    ]:
        accounts.append(dict(id=ident, name=name, institution='Demo Institution',
            kind=kind, balance=balance, transactionCount=0, sourceType='local',
            sourceLabel='Synthetic demo', lastSync='2026-06-03T12:00:00Z'))
    transactions = []
    for month in range(1, 7):
        rows = [
            (1, 'Demo Salary', 'Income', 4600 + 100 * month, 0, False),
            (2, 'Demo Rent', 'Housing', -1550, 0, False),
            (5, 'Demo Grocer', 'Groceries', -220 - 12 * month, 2, False),
            (8, 'Demo Transit', 'Transport', -65, 2, False),
            (10, 'Demo Studio', 'Subscriptions', -24, 2, False),
            (12, 'Demo Market', 'Groceries', -140 - 7 * month, 2, False),
            (15, 'Demo Cafe', 'Dining', -48 - 4 * month, 2, False),
            (17, 'Demo Utilities', 'Utilities', -95 - 3 * month, 0, False),
            (20, 'Card payment', 'Payment', -900, 0, True),
            (20, 'Payment thank you', 'Payment', 900, 2, True),
            (22, 'Savings transfer', 'Transfer', -500, 0, True),
            (22, 'Savings transfer', 'Transfer', 500, 1, True),
            (25, 'Demo Card Refund', 'Refund', 45, 2, False),
            (27, 'Demo Account Fee', 'Fees', -5, 0, False),
        ]
        for day, description, category, amount, ai, transfer in rows:
            a = accounts[ai]
            # The final demo month deliberately ends on June 3.
            day = min(day, 3) if month == 6 else day
            transactions.append(dict(id=f'demo-{len(transactions):03}',
                date=f'2026-{month:02}-{day:02}', description=description,
                category=category, amount=amount, accountId=a['id'],
                accountName=a['name'], institution=a['institution'],
                accountKind=a['kind'], sourceFile='Synthetic demonstration.csv',
                isTransfer=transfer))
    transactions.sort(key=lambda x: x['date'], reverse=True)
    for account in accounts:
        account['transactionCount'] = sum(t['accountId'] == account['id'] for t in transactions)
    history = []
    for month in range(1, 7):
        for a in accounts:
            multiplier = 0.78 + (month - 1) * 0.044
            history.append(dict(accountId=a['id'], institution=a['institution'],
                accountName=a['name'], kind=a['kind'],
                balance=round(a['balance'] * multiplier, 2),
                snapshotDate=f'2026-{month:02}-03'))
    holdings = []
    for ticker, name, kind, quantity, price in [
        ('DEMO-A', 'Demo Broad Equity Fund', 'etf', 100, 140),
        ('DEMO-B', 'Demo Bond Fund', 'etf', 100, 65),
        ('DEMO-C', 'Demo Cash Fund', 'cash', 4000, 1),
    ]:
        holdings.append(dict(accountId='demo-brokerage', institution='Demo Institution',
            accountName='Demo Brokerage', securityId=ticker, securityName=name,
            ticker=ticker, type=kind, quantity=quantity, price=price,
            value=quantity * price, costBasis=None, currency='USD',
            priceAsOf='2026-06-03', lastSync='2026-06-03T12:00:00Z'))
    return dict(accounts=accounts, transactions=transactions,
        sourceFiles=['Synthetic demonstration.csv'], ignoredFiles=[],
        importRecords=[], accountSnapshots=[], investmentHoldings=holdings,
        balanceHistory=history, manualEdits=dict(selectedTransactionIds=[], monthlyRecords=[]))


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--url', default='http://127.0.0.1:3105')
    args = parser.parse_args()
    fixture = make_demo()
    ASSETS.mkdir(parents=True, exist_ok=True)
    (ASSETS / 'demo-data.json').write_text(json.dumps(fixture, indent=2) + '\n')
    with sync_playwright() as p:
        browser = p.chromium.launch(channel='chrome', headless=True)
        page = browser.new_page(viewport={'width': 1440, 'height': 1050}, device_scale_factor=1.5)
        def intercept(route):
            if route.request.url.split('?')[0].endswith('/api/data'):
                route.fulfill(json=fixture)
            else:
                route.fulfill(status=200, json={})
        page.route('**/api/**', intercept)
        page.goto(args.url, wait_until='networkidle')
        page.get_by_text('Monthly Money Flow', exact=True).wait_for()
        page.evaluate('document.fonts.ready')
        page.screenshot(path=str(ASSETS / 'dashboard-overview.png'))
        page.get_by_role('button', name='Brokerage', exact=True).click()
        page.get_by_text('Brokerage Value Trend', exact=True).wait_for()
        page.screenshot(path=str(ASSETS / 'dashboard-brokerage.png'))
        page.get_by_role('button', name='Transactions', exact=True).click()
        page.get_by_text('Transaction Detail', exact=True).wait_for()
        page.get_by_text('Demo Salary', exact=True).first.click()
        page.screenshot(path=str(ASSETS / 'dashboard-transactions.png'))
        browser.close()
    print('Captured 3 real UI views with synthetic data; all finance APIs intercepted.')

if __name__ == '__main__':
    main()
