"""Print resolved session context paths for interactive use.

Usage:
    python3 -m mixersystem context --session_folder=<path>

Prints all file paths that an artifact builder would receive:
artifacts, family, docs, rules, questions, and session config.
"""

from pathlib import Path

from mixersystem.data.repository import get_context, run_cli

STAGES = ("task", "plan", "work", "update", "upgrade", "report")


async def run(**kwargs):
    ctx = get_context()
    sf = Path(ctx.session_folder)
    lines: list[str] = []

    # -- Artifacts --
    artifacts = [sf / f"{s}.md" for s in STAGES if (sf / f"{s}.md").is_file()]
    if artifacts:
        lines.append("## Artifacts")
        for p in artifacts:
            lines.append(str(p))

    # -- Questions (with answers) --
    q_files = [sf / f"{s}_questions.json" for s in STAGES if (sf / f"{s}_questions.json").is_file()]
    if q_files:
        lines.append("")
        lines.append("## Questions")
        for p in q_files:
            lines.append(str(p))

    # -- Family context --
    family = ctx.resolve_family()
    if family:
        paths = _extract_paths(family)
        if paths:
            lines.append("")
            lines.append("## Family")
            for p in paths:
                lines.append(p)

    # -- Docs --
    docs = ctx.resolve_docs()
    if docs:
        paths = _extract_paths(docs)
        if paths:
            lines.append("")
            lines.append("## Docs")
            for p in paths:
                lines.append(p)

    # -- Rules (all stages) --
    rule_paths: list[str] = []
    seen = set()
    for stage in STAGES:
        rules = ctx.resolve_rules(stage)
        if rules:
            for p in _extract_paths(rules):
                if p not in seen:
                    seen.add(p)
                    rule_paths.append(p)
    if rule_paths:
        lines.append("")
        lines.append("## Rules")
        for p in rule_paths:
            lines.append(p)

    # -- Session config --
    session_json = sf / "session.json"
    if session_json.is_file():
        lines.append("")
        lines.append("## Session")
        lines.append(str(session_json))

    print("\n".join(lines))


def _extract_paths(resolved_text: str) -> list[str]:
    """Extract file paths from resolve_* output (lines like '   - ./path/to/file')."""
    paths = []
    project_root = str(get_context().project_root or "")
    for line in resolved_text.splitlines():
        stripped = line.strip()
        if stripped.startswith("- "):
            rel = stripped[2:].strip()
            if rel.startswith("./") and project_root:
                paths.append(str(Path(project_root) / rel[2:]))
            else:
                paths.append(rel)
        elif stripped.startswith("[") and stripped.endswith("]"):
            # Section label like [.mixer/sessions/parent], skip
            continue
    return paths


if __name__ == "__main__":
    run_cli(run)
