"""albus pathway -- Pathway lifecycle commands."""

from __future__ import annotations

import asyncio
import hashlib
from pathlib import Path

from server.transport.cli._models import PathwayArgs


def cmd_pathway(args: PathwayArgs) -> int:
    """Pathway lifecycle commands."""
    if args.action == "list":
        return _pathway_list(args)
    if args.action == "new":
        return _pathway_new(args)
    if args.action == "validate":
        return _pathway_validate(args)
    if args.action == "export":
        return _pathway_export(args)
    if args.action == "load":
        return _pathway_load(args)
    if args.action == "hash":
        return _pathway_hash(args)
    print(f"Unknown action: {args.action}")
    return 2


def _pathway_list(args: PathwayArgs) -> int:
    """List registered pathways."""

    async def _list() -> int:
        import aiohttp

        url = f"http://{args.host}:{args.port}/api/v1/pathways"
        try:
            async with aiohttp.ClientSession() as session, session.get(url) as resp:
                data = await resp.json()
                paths = data.get("pathways", [])
                print(f"Pathways ({len(paths)}):")
                for p in paths:
                    mode = p.get("mode", "dag")
                    version = p.get("version", "")
                    v_str = f" v{version}" if version else ""
                    print(f"  {p.get('id')} ({mode}{v_str})")
                return 0
        except Exception as e:
            print(f"Error: {e}")
            return 1

    return asyncio.run(_list())


def _pathway_new(args: PathwayArgs) -> int:
    """Create a new pathway scaffold."""
    pathway_id = (args.id or "").strip()
    if not pathway_id:
        print("Error: pathway id required")
        return 2

    scaffold = f"""# {pathway_id.replace("_", " ").title()}
# Created with: albus pathway new {pathway_id}

id: {pathway_id}
name: {pathway_id.replace("_", " ").title()}
description: |
  TODO: Describe what this pathway does.
mode: {args.mode}
version: "1.0.0"

nodes:
  input:
    type: input
    input_schema:
      query:
        type: string
        description: "Input query"
    description: "Pathway input"

  process:
    type: llm
    prompt: "Process this: {{{{input.query}}}}"
    model: reasoning
    description: "Process the input"

  output:
    type: output
    mapping:
      result: "{{{{process.output.content}}}}"
    description: "Pathway output"

connections:
  - from_node: input
    to_node: process
  - from_node: process
    to_node: output

metadata:
  category: custom
  tags:
    - todo
"""

    if args.output:
        Path(args.output).write_text(scaffold)
        print(f"\u2713 Created: {args.output}")
    else:
        print(scaffold)

    return 0


def _pathway_validate(args: PathwayArgs) -> int:
    """Validate a pathway YAML."""
    target = (args.target or "").strip()
    if not target:
        print("Error: pathway file required")
        return 2

    target_path = Path(target)
    if not target_path.exists():
        print(f"Error: File not found: {target}")
        return 1

    try:
        from core.pathways.context import Context
        from core.pathways.pathway import Pathway
        from core.pathways.validation import validate_pathway
        from core.tools import get_tool_registry
        from stdlib.bootstrap import load_stdlib

        load_stdlib()

        yaml_content = target_path.read_text()
        pathway = Pathway.from_yaml(yaml_content)

        registry = get_tool_registry()
        ctx = Context(tools={td.name: td.handler for td in registry.list() if td.handler})
        result = validate_pathway(pathway, ctx)

        if not result.valid:
            print(f"\u274c Validation failed: {target}")
            for e in result.errors:
                print(f"  - {e}")
            return 1

        print(f"\u2713 Valid: {pathway.id} ({pathway.mode.value}, {len(pathway.nodes)} nodes)")
        if pathway.version:
            print(f"  Version: {pathway.version}")
        if result.warnings:
            print("  Warnings:")
            for w in result.warnings:
                print(f"    - {w}")

        return 0
    except Exception as e:
        print(f"\u274c Parse error: {e}")
        return 1


def _pathway_export(args: PathwayArgs) -> int:
    """Export a registered pathway to YAML."""
    pathway_id = (args.id or "").strip()
    if not pathway_id:
        print("Error: pathway id required")
        return 2

    async def _export() -> int:
        import aiohttp

        url = f"http://{args.host}:{args.port}/api/v1/pathways/{pathway_id}/export"
        try:
            async with aiohttp.ClientSession() as session, session.get(url) as resp:
                if resp.status == 404:
                    print(f"Error: Pathway '{pathway_id}' not found")
                    return 1
                data = await resp.json()

                from core.pathways.loader import pathway_from_dict

                pathway = pathway_from_dict(data.get("pathway", {}))
                json_content = pathway.model_dump_json(indent=2, exclude_none=True)

                if args.output:
                    Path(args.output).write_text(json_content)
                    print(f"\u2713 Exported: {args.output}")
                else:
                    print(json_content)
                return 0
        except Exception as e:
            print(f"Error: {e}")
            return 1

    return asyncio.run(_export())


def _pathway_load(args: PathwayArgs) -> int:
    """Load a pathway YAML into the server registry."""
    target = (args.target or "").strip()
    if not target:
        print("Error: pathway file required")
        return 2

    target_path = Path(target)
    if not target_path.exists():
        print(f"Error: File not found: {target}")
        return 1

    async def _load() -> int:
        import aiohttp

        from core.pathways.pathway import Pathway

        yaml_content = target_path.read_text()
        try:
            pathway = Pathway.from_yaml(yaml_content)
        except Exception as e:
            print(f"Error parsing YAML: {e}")
            return 1

        url = f"http://{args.host}:{args.port}/api/v1/pathways/import"
        payload = {
            "format": "server.pathway.v1",
            "pathway": pathway.model_dump(mode="json"),
        }

        try:
            async with aiohttp.ClientSession() as session:
                async with session.post(url, json=payload) as resp:
                    data = await resp.json()
                    if data.get("success"):
                        print(f"\u2713 Loaded: {pathway.id} ({pathway.mode.value})")
                        return 0
                    print(f"Error: {data.get('error', 'Unknown')}")
                    return 1
        except Exception as e:
            print(f"Error: {e}")
            return 1

    return asyncio.run(_load())


def _pathway_hash(args: PathwayArgs) -> int:
    """Get content hash of a pathway YAML (for CI/CD)."""
    target = (args.target or "").strip()
    if not target:
        print("Error: pathway file required")
        return 2

    target_path = Path(target)
    if not target_path.exists():
        print(f"Error: File not found: {target}")
        return 1

    try:
        from core.pathways.pathway import Pathway

        yaml_content = target_path.read_text()
        pathway = Pathway.from_yaml(yaml_content)

        normalized = pathway.model_dump_json(exclude_none=True)
        content_hash = hashlib.sha256(normalized.encode()).hexdigest()[:16]

        print(f"{content_hash}  {target}")
        return 0
    except Exception as e:
        print(f"Error: {e}")
        return 1
