"""Bounded anonymous recursive retrieval. Full SQLite journal; no biological writes or automatic review.

Downloadable reference client: python recursive-client.py --seed creatine --journal creatine.sqlite3
Requires httpx. Resume with the same journal and configuration. Budgets apply to each run.
"""
import argparse
import hashlib
import json
from pathlib import Path
import sqlite3
from urllib.parse import quote, urlsplit


class Journal:
    def __init__(self, path, origin, seeds, limit=25):
        origin = origin.rstrip('/')
        parsed = urlsplit(origin)
        if parsed.scheme not in ('http', 'https') or not parsed.netloc or parsed.path or parsed.query or parsed.fragment or parsed.username:
            raise ValueError('Use an HTTP(S) origin without credentials, path or query')
        if not seeds or not all(isinstance(s, str) and s.strip() for s in seeds) or not 1 <= limit <= 200:
            raise ValueError('Provide exact seeds and a page limit from 1 to 200')
        self.origin, self.limit = origin, limit
        self.db = sqlite3.connect(path, timeout=1)
        self.db.row_factory = sqlite3.Row
        self.db.executescript('''
            CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS nodes(slug TEXT PRIMARY KEY, depth INTEGER NOT NULL,
                priority INTEGER NOT NULL, status TEXT NOT NULL, next_url TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS pages(id INTEGER PRIMARY KEY, slug TEXT NOT NULL,
                url TEXT UNIQUE NOT NULL, sha256 TEXT NOT NULL, payload TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS arrivals(page_id INTEGER, from_slug TEXT, to_slug TEXT,
                connection_key TEXT, detail TEXT, PRIMARY KEY(page_id,to_slug,connection_key));
            CREATE INDEX IF NOT EXISTS arrival_target ON arrivals(to_slug);
            CREATE TABLE IF NOT EXISTS edges(from_slug TEXT, to_slug TEXT, PRIMARY KEY(from_slug,to_slug));
        ''')
        config = {'schema': 1, 'origin': origin, 'seeds': sorted(set(seeds)), 'limit': limit}
        old = self.meta('config')
        if old and old != config:
            self.close()
            raise ValueError('Journal configuration differs; preserve this journal and create a separate run')
        with self.db:
            self.set_meta('config', config)
            for slug in seeds:
                self.db.execute('INSERT OR IGNORE INTO nodes VALUES (?,0,-1,\'pending\',?)',
                                (slug, self.url(slug)))
            # Backfill topology when resuming an older journal; full packets are authoritative.
            for page in self.db.execute('SELECT slug,payload FROM pages'):
                for branch in json.loads(page['payload'])['recursive_discovery']['branches']:
                    self.db.execute('INSERT OR IGNORE INTO edges VALUES (?,?)', (page['slug'], branch['slug']))
            self._relax_depths()

    def url(self, slug):
        return '/api/v1/discovery/mechanisms/' + quote(slug, safe='') + '?limit=' + str(self.limit)

    def meta(self, key):
        row = self.db.execute('SELECT value FROM metadata WHERE key=?', (key,)).fetchone()
        return json.loads(row[0]) if row else None

    def set_meta(self, key, value):
        self.db.execute('INSERT OR REPLACE INTO metadata VALUES (?,?)', (key, json.dumps(value, ensure_ascii=False)))

    def _relax_depths(self):
        # Focus may discover a shorter route to an already expanded node. Propagate that
        # distance through retained descendants before enforcing the next depth boundary.
        while True:
            self.db.execute('''UPDATE nodes SET depth=(
                SELECT min(parent.depth+1) FROM edges a JOIN nodes parent ON parent.slug=a.from_slug
                WHERE a.to_slug=nodes.slug)
                WHERE depth>(SELECT min(parent.depth+1) FROM edges a
                JOIN nodes parent ON parent.slug=a.from_slug WHERE a.to_slug=nodes.slug)''')
            if not self.db.execute('SELECT changes()').fetchone()[0]:
                return

    def run(self, client, *, max_pages=20, max_depth=2, max_nodes=8, focus=()):
        if max_pages < 1 or max_depth < 0 or max_nodes < 1:
            raise ValueError('Use positive page/node budgets and nonnegative depth')
        if self.meta('stopped_reason') == 'revision_conflict':
            raise RuntimeError('Explicit preserved-state refresh plan required; retain this journal')
        guide = client.get(self.origin + '/api/v1/discovery')
        guide.raise_for_status()
        with self.db:
            self.set_meta('runtime_guide', guide.json())
            self.set_meta('run_scope', {'max_pages': max_pages, 'max_depth': max_depth, 'max_nodes': max_nodes, 'focus': list(focus)})
        expanded = set()
        for _ in range(max_pages):
            try:
                # Single writer across selection, network retrieval and durable state update.
                self.db.execute('BEGIN IMMEDIATE')
                rows = self.db.execute("SELECT * FROM nodes WHERE status!='complete' AND depth<=? ORDER BY depth,priority,slug", (max_depth,)).fetchall()
                if not rows:
                    pending = self.db.execute("SELECT count(*) FROM nodes WHERE status!='complete'").fetchone()[0]
                    self.set_meta('stopped_reason', 'depth_boundary' if pending else 'recorded_frontier_exhausted')
                    self.db.commit(); return self.report()
                eligible = [r for r in rows if len(expanded) < max_nodes or r['slug'] in expanded]
                if not eligible:
                    self.set_meta('stopped_reason', 'node_budget'); self.db.commit(); return self.report()
                # Focus is a disclosed prioritization, never an allow-list or a new unconnected seed.
                node = next((r for s in focus for r in eligible if r['slug'] == s), eligible[0])
                url = node['next_url']
                parsed = urlsplit(url)
                if parsed.scheme or parsed.netloc or not parsed.path.startswith('/api/v1/discovery/mechanisms/'):
                    raise ValueError('Unexpected continuation URL; journal preserved')
                response = client.get(self.origin + url)
                if response.status_code in (409, 422):
                    raise RuntimeError('Explicit preserved-state refresh plan required: ' + response.text[:400])
                response.raise_for_status()
                packet = response.json()
                if packet.get('entity', {}).get('slug') != node['slug'] or 'recursive_discovery' not in packet:
                    raise ValueError('Unexpected or older mechanism packet; journal preserved')
                revision = [packet['selection'][k] for k in ('ledger_revision','navigation_version','structured_revision')]
                old = self.meta('revision')
                if old and old != revision:
                    raise RuntimeError('Explicit preserved-state refresh plan required: revision changed between nodes')
                self.set_meta('revision', revision)
                payload = json.dumps(packet, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
                page_id = self.db.execute('INSERT INTO pages(slug,url,sha256,payload) VALUES (?,?,?,?)',
                    (node['slug'], url, hashlib.sha256(payload.encode()).hexdigest(), payload)).lastrowid
                following = packet['pagination']['next']
                self.db.execute('UPDATE nodes SET status=?,next_url=? WHERE slug=?',
                                ('partial' if following else 'complete', following or '', node['slug']))
                for branch in packet['recursive_discovery']['branches']:
                    target = branch['slug']
                    self.db.execute('INSERT OR IGNORE INTO edges VALUES (?,?)', (node['slug'], target))
                    self.db.execute('''INSERT INTO nodes VALUES (?,?,?,'pending',?) ON CONFLICT(slug) DO UPDATE SET
                        depth=min(depth,excluded.depth), priority=min(priority,excluded.priority)''',
                        (target, node['depth']+1, branch['priority'], branch['url']))
                    for arrival in branch['arrivals']:
                        self.db.execute('INSERT INTO arrivals VALUES (?,?,?,?,?)',
                            (page_id, node['slug'], target, arrival['connection_key'], json.dumps(arrival, ensure_ascii=False)))
                self._relax_depths()
                self.set_meta('stopped_reason', 'page_budget')
                self.db.commit()
                expanded.add(node['slug'])
            except Exception as exc:
                self.db.rollback()
                with self.db:
                    self.set_meta('stopped_reason', 'revision_conflict' if 'refresh plan' in str(exc) else 'request_failed')
                    self.set_meta('last_error', str(exc))
                raise
        return self.report()

    def report(self):
        frontier = [dict(r) for r in self.db.execute('SELECT * FROM nodes ORDER BY depth,priority,slug')]
        return {'schema': 'ledger.recursive-journal.v1', 'config': self.meta('config'), 'revision': self.meta('revision'),
                'run_scope': self.meta('run_scope'), 'stopped_reason': self.meta('stopped_reason'),
                'retrieval': {'pages': self.db.execute('SELECT count(*) FROM pages').fetchone()[0],
                              'complete_nodes': sum(n['status']=='complete' for n in frontier),
                              'partial_nodes': sum(n['status']=='partial' for n in frontier),
                              'pending_nodes': sum(n['status']=='pending' for n in frontier),
                              'arrivals': self.db.execute('SELECT count(*) FROM arrivals').fetchone()[0]},
                'scientific_review': {'reviewed_nodes': 0, 'status': 'not_assessed',
                    'notice': 'This client retrieves evidence. Attach substantive human/agent review notes separately; downloading never marks scientific review.'},
                'frontier': frontier}

    def pages(self):
        return [{**dict(r), 'payload': json.loads(r['payload'])} for r in self.db.execute('SELECT * FROM pages ORDER BY id')]

    def arrivals(self):
        return [{**dict(r), 'detail': json.loads(r['detail'])} for r in self.db.execute('SELECT * FROM arrivals ORDER BY page_id,to_slug,connection_key')]

    def close(self):
        self.db.close()


def main():
    import httpx
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--origin', default='https://mechanismledger.com')
    parser.add_argument('--seed', action='append', required=True)
    parser.add_argument('--journal', type=Path, required=True)
    parser.add_argument('--limit', type=int, default=25)
    parser.add_argument('--max-pages', type=int, default=20)
    parser.add_argument('--max-nodes', type=int, default=8)
    parser.add_argument('--max-depth', type=int, default=2)
    parser.add_argument('--focus', action='append', default=[])
    parser.add_argument('--export', type=Path)
    args = parser.parse_args()
    if args.export and (args.export.resolve() == args.journal.resolve() or
                        (args.export.exists() and args.journal.exists() and args.export.samefile(args.journal))):
        parser.error('--export must name a different file from --journal; preserve the SQLite journal')
    journal = Journal(args.journal, args.origin, args.seed, args.limit)
    try:
        with httpx.Client(timeout=60, headers={'User-Agent':'MechanismLedger-RecursiveClient/1.0'}) as client:
            journal.run(client, max_pages=args.max_pages, max_nodes=args.max_nodes, max_depth=args.max_depth, focus=args.focus)
        if args.export:
            args.export.write_text(json.dumps({'report':journal.report(),'pages':journal.pages(),'arrivals':journal.arrivals()}, ensure_ascii=False, indent=2), encoding='utf-8')
        print(json.dumps(journal.report(), ensure_ascii=False, indent=2))
    finally:
        journal.close()


if __name__ == '__main__':
    main()
