
import sqlite3
import os

db_path = 'law_risk.db'

def inspect_db():
    if not os.path.exists(db_path):
        print(f"Database not found at {db_path}")
        return

    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # List tables
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    print("Tables:")
    for table in tables:
        print(table[0])
    
    print("\n--- Schemas ---\n")
    for table in tables:
        table_name = table[0]
        cursor.execute(f"PRAGMA table_info({table_name})")
        columns = cursor.fetchall()
        print(f"Table: {table_name}")
        for col in columns:
            print(col)
        print("-" * 20)

    print("\n--- Searching for Theme ---\n")
    try:
        # Assuming table is legal_risk_theme based on previous grep, checking anyway
        cursor.execute("SELECT * FROM themes WHERE name LIKE '%企业开办%'")
        themes = cursor.fetchall()
        print("Matching Themes:")
        for theme in themes:
            print(theme)
            
        if themes:
            theme_id = themes[0][0] # Assuming first col is ID
            print(f"\nSearching for items with theme_id: {theme_id}")
            # Try to find table that links theme and items. legal_risk_licensing_item?
            print(f"Theme ID: {theme_id}")
            cursor.execute(f"SELECT * FROM region_theme_permits WHERE theme_id = '{theme_id}'")
            links = cursor.fetchall()
            print(f"Associated Links ({len(links)}):")
            for link in links:
                print(link)
                permit_id = link[2]
                cursor.execute(f"SELECT * FROM permits WHERE id = '{permit_id}'")
                permit = cursor.fetchone()
                print(f"  -> Permit: {permit}")

    except Exception as e:
        print(f"Error querying data: {e}")

    conn.close()

if __name__ == "__main__":
    inspect_db()
