import os
import sys
import sqlite3


def extract_insert_statements(sql_path):
    statements = []
    buffer = []
    capturing = False

    with open(sql_path, "r", encoding="utf-8", errors="ignore") as handle:
        for line in handle:
            stripped = line.strip()
            if not stripped:
                continue
            if stripped.startswith("INSERT INTO"):
                capturing = True
                buffer = [line]
                if stripped.endswith(";"):
                    statements.append("".join(buffer))
                    buffer = []
                    capturing = False
                continue
            if capturing:
                buffer.append(line)
                if stripped.endswith(";"):
                    statements.append("".join(buffer))
                    buffer = []
                    capturing = False

    return statements


def create_schema(sqlite_path):
    repo_root = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
    sys.path.insert(0, repo_root)

    from app import create_app
    from app.extensions import db

    os.environ.setdefault("DB_CONNECTION", "sqlite")
    os.environ.setdefault("DB_DATABASE", sqlite_path)
    os.environ.setdefault("FLASK_ENV", "development")

    app = create_app("development")
    with app.app_context():
        db.create_all()


def import_data(sqlite_path, sql_path):
    conn = sqlite3.connect(sqlite_path)
    conn.execute("PRAGMA foreign_keys = OFF")
    cursor = conn.cursor()

    statements = extract_insert_statements(sql_path)
    for statement in statements:
        cursor.execute(statement)

    conn.commit()
    conn.close()


def main():
    if len(sys.argv) < 3:
        print("Usage: import_mysql_dump_to_sqlite.py <mysql_dump.sql> <sqlite_db_path>")
        sys.exit(1)

    sql_path = os.path.abspath(sys.argv[1])
    sqlite_path = os.path.abspath(sys.argv[2])

    if os.path.exists(sqlite_path):
        os.remove(sqlite_path)

    create_schema(sqlite_path)
    import_data(sqlite_path, sql_path)
    print(f"Imported data into {sqlite_path}")


if __name__ == "__main__":
    main()
