use anyhow::Result;

use crate::api::PlaneApiClient;
use crate::config::resolve_plane_session;
use crate::git_context::{BranchInference, infer_work_item_from_branch};

/// Prints the full Plane web URL for the work item inferred from the current git branch.
/// Designed for scripting — outputs only the URL with no decoration.
/// Usage: `plane url` → "https://app.plane.so/jakutainc/projects/.../issues/..."
#[derive(clap::Args)]
pub struct PrintWorkItemUrlArgs;

/// Execution logic for the `plane url` subcommand
impl PrintWorkItemUrlArgs {
    /// Reads the current git branch, resolves the work item via the Plane API,
    /// and prints the browser URL to stdout
    pub async fn execute(self) -> Result<()> {
        let work_item_identifier = match infer_work_item_from_branch() {
            BranchInference::Resolved(identifier) => identifier,
            BranchInference::NotInGitRepo => {
                anyhow::bail!("not in a git repository — cannot infer work item from branch");
            }
            BranchInference::NoIdentifierInBranch(branch_name) => {
                anyhow::bail!(
                    "branch '{}' does not contain a work item identifier (expected pattern like NRO-123)",
                    branch_name
                );
            }
        };

        let plane_session = resolve_plane_session()?;
        let api_client = PlaneApiClient::try_new(plane_session)?;

        let fetched_work_item = api_client
            .find_work_item_by_identifier(&work_item_identifier)
            .await?;

        let mut browser_url = String::with_capacity(128);
        browser_url.push_str("https://app.plane.so/");
        browser_url.push_str(api_client.workspace_slug().as_str());
        browser_url.push_str("/projects/");
        browser_url.push_str(fetched_work_item.project_id().as_str());
        browser_url.push_str("/issues/");
        browser_url.push_str(fetched_work_item.id().as_str());

        println!("{}", browser_url);

        Ok(())
    }
}
