#!/usr/bin/env python3
"""Import existing attestation files into the viewer database."""

import base64
import json
import os
import sys
from pathlib import Path

# Add parent to path for shared code
sys.path.insert(0, str(Path(__file__).parent))
from server import DB_PATH, init_db, extract_metrics, get_db

def main():
    init_db()
    att_dir = Path(__file__).parent.parent / "attestations"

    for f in att_dir.glob("*.json"):
        if f.name == "pre-analysis.json":
            continue
        if f.name.startswith("scan-"):
            continue

        print(f"Importing {f.name}...")
        try:
            with open(f) as fh:
                envelope = json.load(fh)
            payload = json.loads(base64.b64decode(envelope["payload"]))
            name = payload.get("predicate", {}).get("name", f.stem)

            # Extract package name from step name
            pkg = name.replace("pip-install-", "")

            metrics = extract_metrics(str(f))

            # Check pre-analysis
            pre = att_dir / "pre-analysis.json"
            risk_score = 0
            risk_level = "CLEAN"
            if pre.exists():
                try:
                    with open(pre) as ph:
                        pre_data = json.load(ph)
                    risk_score = pre_data.get("risk_score", 0)
                    risk_level = pre_data.get("risk_level", "UNKNOWN")
                except Exception:
                    pass

            db = get_db()
            db.execute("""
                INSERT INTO scans (package, status, risk_score, risk_level,
                    started_at, completed_at, attestation_path, pre_analysis_path,
                    network_connections, files_opened, processes_spawned,
                    dns_lookups, sockets_created, packages_installed)
                VALUES (?, 'completed', ?, ?, datetime('now'), datetime('now'), ?, ?, ?, ?, ?, ?, ?, ?)
            """, (
                pkg, risk_score, risk_level, str(f),
                str(pre) if pre.exists() else None,
                metrics["network_connections"], metrics["files_opened"],
                metrics["processes_spawned"], metrics["dns_lookups"],
                metrics["sockets_created"], metrics["packages_installed"],
            ))
            db.commit()
            db.close()
            print(f"  Imported: {pkg} (risk={risk_level}, net={metrics['network_connections']})")
        except Exception as e:
            print(f"  Error: {e}")


if __name__ == "__main__":
    main()
