// Module: src/main.ts
// UUIDv7: 01a22b63-88c8-785a-a2dc-3f9ea3b50e45
// Timestamp: 2026-11-30T07:37:53.096053+00:00

import { StorageController } from "./storage";
import { TaxonomyEngine } from "./taxonomy";
import { VersioningEngine } from "./versioning";
import { IntegrityGuardEngine } from "./integrity";
import { LogItemEngine } from "./log_items";
import { SerializationEngine } from "./serialization";
import { DynamicAuditEngine } from "./audit";
import { BannerController } from "./banner";
import { PromptTableComponent } from "./prompt_table";
import { WorkspaceComponent } from "./workspace";
import { UUIDv7 } from "./types";
import { UUIDv7Generator } from "./uuid";

export class Application {
  private storageController: StorageController;
  private taxonomyEngine: TaxonomyEngine;
  private versioningEngine: VersioningEngine;
  private integrityEngine: IntegrityGuardEngine;
  private logItemEngine: LogItemEngine;
  private serializationEngine: SerializationEngine;
  private auditEngine: DynamicAuditEngine;
  private bannerController: BannerController;

  private root: HTMLElement;
  private tableComponent: PromptTableComponent | null = null;
  private workspaceComponent: WorkspaceComponent | null = null;

  constructor() {
    this.storageController = new StorageController();
    this.taxonomyEngine = new TaxonomyEngine(this.storageController);
    this.versioningEngine = new VersioningEngine(this.storageController);
    this.integrityEngine = new IntegrityGuardEngine(this.storageController);
    this.logItemEngine = new LogItemEngine(this.storageController);
    this.serializationEngine = new SerializationEngine(this.storageController);
    this.auditEngine = new DynamicAuditEngine(this.storageController);
    this.bannerController = new BannerController();

    this.root = document.getElementById("app") || document.body;
  }

  public bootstrap(): void {
    this.bannerController.init();
    this.storageController.initialize();
    this.seedIfEmpty();

    window.addEventListener("hashchange", () => this.handleRoute());
    window.addEventListener("storage:committed", () => {
      this.auditEngine.renderHUDToDOM();
    });

    this.handleRoute();
    this.auditEngine.renderHUDToDOM();
    this.bindGlobalActions();
  }

  private handleRoute(): void {
    const hash = window.location.hash;
    const match = hash.match(/^#\/prompt\/([0-9a-fA-F-]+)$/);

    if (match) {
      const promptId = match[1];
      try {
        this.mountWorkspace(promptId);
      } catch (e: any) {
        this.bannerController.showBanner("route-error", `Prompt '${promptId}' not found. Redirected to index.`, "warning");
        window.location.hash = "#/";
        this.mountTable();
      }
    } else {
      this.mountTable();
    }
    this.auditEngine.renderHUDToDOM();
  }

  private mountTable(): void {
    this.root.innerHTML = `<div id="table-mount"></div>`;
    const container = document.getElementById("table-mount")!;
    this.tableComponent = new PromptTableComponent(
      container,
      this.storageController,
      this.logItemEngine,
      (id: UUIDv7) => { window.location.hash = `#/prompt/${id}`; },
      () => { this.createNewPrompt(); }
    );
    this.tableComponent.mount();
  }

  private mountWorkspace(promptId: UUIDv7): void {
    this.root.innerHTML = `<div id="ws-mount"></div>`;
    const container = document.getElementById("ws-mount")!;
    this.workspaceComponent = new WorkspaceComponent(
      container,
      this.storageController,
      this.taxonomyEngine,
      this.versioningEngine,
      this.integrityEngine,
      this.logItemEngine,
      () => { window.location.hash = "#/"; }
    );
    this.workspaceComponent.mount(promptId);
  }

  private createNewPrompt(): void {
    const pId = UUIDv7Generator.generate();
    const vId = UUIDv7Generator.generate();

    this.storageController.commitTransaction((draft) => {
      draft.prompts.push({
        id: pId,
        title: "Untitled Prompt",
        category_id: null,
        pipeline_id: null,
        workflow_id: null,
        tags: ["draft"],
        active_version_id: vId,
        updated_at: new Date().toISOString(),
      });
      draft.versions.push({
        id: vId,
        prompt_id: pId,
        version_num: 1,
        body: "Enter prompt template instructions...",
        system_notes: "Initial creation.",
        created_at: new Date().toISOString(),
      });
    });

    window.location.hash = `#/prompt/${pId}`;
  }

  private bindGlobalActions(): void {
    document.addEventListener("click", (e: any) => {
      if (e.target.id === "btn-theme-toggle") {
        const next = document.documentElement.getAttribute("data-theme") === "dark" ? "light" : "dark";
        document.documentElement.setAttribute("data-theme", next);
        document.documentElement.style.colorScheme = next;
        this.storageController.commitTransaction((d) => { d.theme = next; });
      }

      if (e.target.id === "btn-export-backup") {
        const json = this.serializationEngine.exportStateAsJSON();
        const blob = new Blob([json], { type: "application/json" });
        const a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = `prompt_manager_backup_${new Date().toISOString().slice(0, 10)}.json`;
        a.click();
      }
    });

    document.addEventListener("change", (e: any) => {
      if (e.target.id === "input-import-file") {
        const file = e.target.files?.[0];
        if (!file) return;
        const reader = new FileReader();
        reader.onload = (ev) => {
          try {
            const raw = ev.target?.result as string;
            const parsed = this.serializationEngine.parseAndValidate(raw);
            if (confirm("Click OK to Merge by ID, or Cancel to Overwrite All.")) {
              this.serializationEngine.executeMergeById(parsed);
            } else if (confirm("WARNING: Overwrite will delete existing records. Proceed?")) {
              this.serializationEngine.executeOverwrite(parsed);
            }
            this.handleRoute();
          } catch (err: any) {
            this.bannerController.showBanner("import-err", err.message, "danger");
          }
        };
        reader.readAsText(file);
      }
    });
  }

  private seedIfEmpty(): void {
    const snap = this.storageController.getSnapshot();
    if (snap.prompts.length === 0) {
      this.storageController.commitTransaction((draft) => {
        const cat = { id: "019364a0-0001-7000-8000-000000000001", name: "Production", updated_at: new Date().toISOString() };
        const pipe = { id: "019364a0-0002-7000-8000-000000000002", category_id: cat.id, name: "Customer Support", updated_at: new Date().toISOString() };
        const work = { id: "019364a0-0003-7000-8000-000000000003", pipeline_id: pipe.id, name: "Triage", updated_at: new Date().toISOString() };
        const pId = "019364a0-0004-7000-8000-000000000004";
        const vId = "019364a0-0005-7000-8000-000000000005";

        draft.categories.push(cat);
        draft.pipelines.push(pipe);
        draft.workflows.push(work);
        draft.prompts.push({
          id: pId,
          title: "Production Escalation Router",
          category_id: cat.id,
          pipeline_id: pipe.id,
          workflow_id: work.id,
          tags: ["support", "router", "v1"],
          active_version_id: vId,
          updated_at: new Date().toISOString(),
        });
        draft.versions.push({
          id: vId,
          prompt_id: pId,
          version_num: 1,
          body: "You are an escalation routing assistant. Classify the user query into billing, technical, or account issues.",
          system_notes: "Initial production baseline.",
          created_at: new Date().toISOString(),
        });
        draft.log_items.push({
          id: "019364a0-0006-7000-8000-000000000006",
          prompt_id: pId,
          version_id: vId,
          type: "issue",
          status: "open",
          content: "Verify international currency handling in query routing.",
          created_at: new Date().toISOString(),
        });
      });
    }
  }
}

if (typeof window !== "undefined") {
  window.addEventListener("DOMContentLoaded", () => new Application().bootstrap());
}