"""ADW Phase: Plan — Analyze issue, generate spec, create implementation plan.
Connects to factory agents for research assistance."""
import sys, json, os
from pathlib import Path

def analyze_issue(issue_number, title, body):
    plan = {
        "issue": issue_number,
        "title": title,
        "type": "feature",
        "spec_path": f"specs/adw-{issue_number}.md",
        "tasks": [],
        "factory_resources": [
            "http://agent-site:8084/factory.html",
            "http://git-proxy:8099/factory-status",
            "http://git-proxy:8099/deploy"
        ]
    }
    body_lower = (title + " " + body).lower()
    if any(w in body_lower for w in ["bug","fix","crash","error"]):
        plan["type"] = "patch"
    elif any(w in body_lower for w in ["refactor","clean"]):
        plan["type"] = "refactor"
    
    plan["tasks"] = [
        {"step": "research", "description": f"Research {title}", "estimated": "5min"},
        {"step": "design", "description": "Design solution approach", "estimated": "10min"},
        {"step": "implement", "description": "Implement changes", "estimated": "30min"},
        {"step": "test", "description": "Write and run tests", "estimated": "15min"},
    ]
    return plan

if __name__ == "__main__":
    issue = int(os.environ.get("ISSUE", sys.argv[sys.argv.index("--issue")+1] if "--issue" in sys.argv else "0"))
    title = "ADW pipeline task"
    body = ""
    plan = analyze_issue(issue, title, body)
    Path("specs").mkdir(exist_ok=True)
    with open(plan["spec_path"], "w") as f:
        f.write(f"# {plan['title']}\n\nType: {plan['type']}\n")
    print(json.dumps(plan, indent=2))
