"""Full local workflow orchestration (Phase 7)."""
from __future__ import annotations

from pathlib import Path
import json
from typing import Dict, Any

from src.knowledge_base import KBIngestionPipeline, OrchestratorExecutor
from src.dbt_integration import (
    DbtProjectGenerator,
    ensure_profiles_yml,
    run_dbt_command,
    load_run_results,
    orchestrator_to_dbt_vars,
)
from src.qa import build_qa_report, write_qa_report


def run_full_workflow(prompt: str = "Generate a GL accounts staging model") -> Dict[str, Any]:
    """Run ingestion -> orchestrator -> dbt scaffold -> dbt tests -> QA report."""
    pipeline = KBIngestionPipeline()
    orchestrator = OrchestratorExecutor(pipeline)
    output = orchestrator.run_query(prompt)

    vars_payload = orchestrator_to_dbt_vars(output, prompt)
    Path("data/qa").mkdir(parents=True, exist_ok=True)
    Path("data/qa/orchestrator_summary.json").write_text(
        json.dumps(vars_payload, indent=2),
        encoding="utf-8",
    )
    generator = DbtProjectGenerator()
    project = generator.get_project("databridge_demo")
    if not project:
        project = generator.create_project(name="databridge_demo", profile="databridge_demo")
    project.config.vars = vars_payload

    project_dir = Path("data/dbt_projects") / project.config.name
    generator.scaffold_project(project, output_path=str(project_dir))
    ensure_profiles_yml(profile_name=project.config.profile)

    results = {}
    try:
        run_dbt_command("test", project_dir)
        run_dbt_command("docs generate", project_dir)
        results = load_run_results(project_dir)
    except Exception as exc:
        results = {"error": str(exc)}

    report = build_qa_report(orchestrator_summary=vars_payload, dbt_results=results, notes="full workflow")
    write_qa_report(report, Path("data/qa/qa_report.json"))
    return report
