import os
import sys
import hashlib
import json
import sqlite3

PROD_DIR = r"C:\xampp\htdocs\Digital Optimus"
ALLOWED_PREFIXES = ("app", "artifacts", "config", "tools", "tests", "trusted_baseline")
EXCLUDED_NAMES = {".git", "__pycache__", ".pytest_cache", ".build_venv", "node_modules", "logs", "cache"}
EXCLUDED_EXTS = {".log", ".db-wal", ".db-shm", ".db-journal", ".tmp"}

def sha256_file(filepath):
    h = hashlib.sha256()
    with open(filepath, "rb") as f:
        while chunk := f.read(65536):
            h.update(chunk)
    return h.hexdigest().upper()

def build_manifest():
    manifest = {}
    for prefix in ALLOWED_PREFIXES:
        p_dir = os.path.join(PROD_DIR, prefix)
        if not os.path.exists(p_dir):
            continue
        for root, dirs, files in os.walk(p_dir):
            dirs[:] = [d for d in dirs if d not in EXCLUDED_NAMES]
            for file in sorted(files):
                ext = os.path.splitext(file)[1].lower()
                if ext in EXCLUDED_EXTS or file.endswith(".pyc") or file.endswith(".log"):
                    continue
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, PROD_DIR).replace("\\", "/")
                try:
                    manifest[rel_path] = sha256_file(full_path)
                except Exception as e:
                    manifest[rel_path] = f"ERROR: {e}"
    
    # Also check root critical files
    for root_file in ["DIGITAL_OPTIMUS_NORTE_MAESTRO.md"]:
        full_path = os.path.join(PROD_DIR, root_file)
        if os.path.isfile(full_path):
            manifest[root_file] = sha256_file(full_path)
            
    return manifest

def check_db():
    db_path = os.path.join(PROD_DIR, "artifacts", "brain_host", "continuity.db")
    if not os.path.exists(db_path):
        return "MISSING"
    try:
        uri = f"file:{db_path}?mode=ro"
        conn = sqlite3.connect(uri, uri=True)
        cur = conn.cursor()
        res = cur.execute("PRAGMA quick_check;").fetchall()
        conn.close()
        return res
    except Exception as e:
        return f"ERROR: {e}"

if __name__ == "__main__":
    action = sys.argv[1] if len(sys.argv) > 1 else "snapshot"
    out_file = sys.argv[2] if len(sys.argv) > 2 else "pre_manifest.json"
    
    m = build_manifest()
    db_st = check_db()
    
    data = {
        "file_count": len(m),
        "db_integrity": db_st,
        "files": m
    }
    with open(out_file, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2)
    print(f"Manifest saved to {out_file}: {len(m)} files, db_check: {db_st}")

